code stringlengths 1 2.08M | language stringclasses 1 value |
|---|---|
/**
* Copyright (c) 2003-2012, CKSource - Frederico Knabben. All rights reserved.
* For licensing, see LICENSE.html or http://ckeditor.com/license
*/
// This file contains style definitions that can be used by CKEditor plugins.
//
// The most common use for it is the "stylescombo" plugin, which shows a combo
// in the editor toolbar, containing all styles. Other plugins instead, like
// the div plugin, use a subset of the styles on their feature.
//
// If you don't have plugins that depend on this file, you can simply ignore it.
// Otherwise it is strongly recommended to customize this file to match your
// website requirements and design properly.
CKEDITOR.stylesSet.add( 'default', [
/* Block Styles */
// These styles are already available in the "Format" combo ("format" plugin),
// so they are not needed here by default. You may enable them to avoid
// placing the "Format" combo in the toolbar, maintaining the same features.
/*
{ name: 'Paragraph', element: 'p' },
{ name: 'Heading 1', element: 'h1' },
{ name: 'Heading 2', element: 'h2' },
{ name: 'Heading 3', element: 'h3' },
{ name: 'Heading 4', element: 'h4' },
{ name: 'Heading 5', element: 'h5' },
{ name: 'Heading 6', element: 'h6' },
{ name: 'Preformatted Text',element: 'pre' },
{ name: 'Address', element: 'address' },
*/
{ name: 'Italic Title', element: 'h2', styles: { 'font-style': 'italic' } },
{ name: 'Subtitle', element: 'h3', styles: { 'color': '#aaa', 'font-style': 'italic' } },
{
name: 'Special Container',
element: 'div',
styles: {
padding: '5px 10px',
background: '#eee',
border: '1px solid #ccc'
}
},
/* Inline Styles */
// These are core styles available as toolbar buttons. You may opt enabling
// some of them in the Styles combo, removing them from the toolbar.
// (This requires the "stylescombo" plugin)
/*
{ name: 'Strong', element: 'strong', overrides: 'b' },
{ name: 'Emphasis', element: 'em' , overrides: 'i' },
{ name: 'Underline', element: 'u' },
{ name: 'Strikethrough', element: 'strike' },
{ name: 'Subscript', element: 'sub' },
{ name: 'Superscript', element: 'sup' },
*/
{ name: 'Marker: Yellow', element: 'span', styles: { 'background-color': 'Yellow' } },
{ name: 'Marker: Green', element: 'span', styles: { 'background-color': 'Lime' } },
{ name: 'Big', element: 'big' },
{ name: 'Small', element: 'small' },
{ name: 'Typewriter', element: 'tt' },
{ name: 'Computer Code', element: 'code' },
{ name: 'Keyboard Phrase', element: 'kbd' },
{ name: 'Sample Text', element: 'samp' },
{ name: 'Variable', element: 'var' },
{ name: 'Deleted Text', element: 'del' },
{ name: 'Inserted Text', element: 'ins' },
{ name: 'Cited Work', element: 'cite' },
{ name: 'Inline Quotation', element: 'q' },
{ name: 'Language: RTL', element: 'span', attributes: { 'dir': 'rtl' } },
{ name: 'Language: LTR', element: 'span', attributes: { 'dir': 'ltr' } },
/* Object Styles */
{
name: 'Styled image (left)',
element: 'img',
attributes: { 'class': 'left' }
},
{
name: 'Styled image (right)',
element: 'img',
attributes: { 'class': 'right' }
},
{
name: 'Compact table',
element: 'table',
attributes: {
cellpadding: '5',
cellspacing: '0',
border: '1',
bordercolor: '#ccc'
},
styles: {
'border-collapse': 'collapse'
}
},
{ name: 'Borderless Table', element: 'table', styles: { 'border-style': 'hidden', 'background-color': '#E6E6FA' } },
{ name: 'Square Bulleted List', element: 'ul', styles: { 'list-style-type': 'square' } }
]);
| JavaScript |
/*
SWFObject v2.2 <http://code.google.com/p/swfobject/>
is released under the MIT License <http://www.opensource.org/licenses/mit-license.php>
*/
;var swfobject=function(){var D="undefined",r="object",S="Shockwave Flash",W="ShockwaveFlash.ShockwaveFlash",q="application/x-shockwave-flash",R="SWFObjectExprInst",x="onreadystatechange",O=window,j=document,t=navigator,T=false,U=[h],o=[],N=[],I=[],l,Q,E,B,J=false,a=false,n,G,m=true,M=function(){var aa=typeof j.getElementById!=D&&typeof j.getElementsByTagName!=D&&typeof j.createElement!=D,ah=t.userAgent.toLowerCase(),Y=t.platform.toLowerCase(),ae=Y?/win/.test(Y):/win/.test(ah),ac=Y?/mac/.test(Y):/mac/.test(ah),af=/webkit/.test(ah)?parseFloat(ah.replace(/^.*webkit\/(\d+(\.\d+)?).*$/,"$1")):false,X=!+"\v1",ag=[0,0,0],ab=null;
if(typeof t.plugins!=D&&typeof t.plugins[S]==r){ab=t.plugins[S].description;if(ab&&!(typeof t.mimeTypes!=D&&t.mimeTypes[q]&&!t.mimeTypes[q].enabledPlugin)){T=true;
X=false;ab=ab.replace(/^.*\s+(\S+\s+\S+$)/,"$1");ag[0]=parseInt(ab.replace(/^(.*)\..*$/,"$1"),10);ag[1]=parseInt(ab.replace(/^.*\.(.*)\s.*$/,"$1"),10);
ag[2]=/[a-zA-Z]/.test(ab)?parseInt(ab.replace(/^.*[a-zA-Z]+(.*)$/,"$1"),10):0;}}else{if(typeof O.ActiveXObject!=D){try{var ad=new ActiveXObject(W);if(ad){ab=ad.GetVariable("$version");
if(ab){X=true;ab=ab.split(" ")[1].split(",");ag=[parseInt(ab[0],10),parseInt(ab[1],10),parseInt(ab[2],10)];}}}catch(Z){}}}return{w3:aa,pv:ag,wk:af,ie:X,win:ae,mac:ac};
}(),k=function(){if(!M.w3){return;}if((typeof j.readyState!=D&&j.readyState=="complete")||(typeof j.readyState==D&&(j.getElementsByTagName("body")[0]||j.body))){f();
}if(!J){if(typeof j.addEventListener!=D){j.addEventListener("DOMContentLoaded",f,false);}if(M.ie&&M.win){j.attachEvent(x,function(){if(j.readyState=="complete"){j.detachEvent(x,arguments.callee);
f();}});if(O==top){(function(){if(J){return;}try{j.documentElement.doScroll("left");}catch(X){setTimeout(arguments.callee,0);return;}f();})();}}if(M.wk){(function(){if(J){return;
}if(!/loaded|complete/.test(j.readyState)){setTimeout(arguments.callee,0);return;}f();})();}s(f);}}();function f(){if(J){return;}try{var Z=j.getElementsByTagName("body")[0].appendChild(C("span"));
Z.parentNode.removeChild(Z);}catch(aa){return;}J=true;var X=U.length;for(var Y=0;Y<X;Y++){U[Y]();}}function K(X){if(J){X();}else{U[U.length]=X;}}function s(Y){if(typeof O.addEventListener!=D){O.addEventListener("load",Y,false);
}else{if(typeof j.addEventListener!=D){j.addEventListener("load",Y,false);}else{if(typeof O.attachEvent!=D){i(O,"onload",Y);}else{if(typeof O.onload=="function"){var X=O.onload;
O.onload=function(){X();Y();};}else{O.onload=Y;}}}}}function h(){if(T){V();}else{H();}}function V(){var X=j.getElementsByTagName("body")[0];var aa=C(r);
aa.setAttribute("type",q);var Z=X.appendChild(aa);if(Z){var Y=0;(function(){if(typeof Z.GetVariable!=D){var ab=Z.GetVariable("$version");if(ab){ab=ab.split(" ")[1].split(",");
M.pv=[parseInt(ab[0],10),parseInt(ab[1],10),parseInt(ab[2],10)];}}else{if(Y<10){Y++;setTimeout(arguments.callee,10);return;}}X.removeChild(aa);Z=null;H();
})();}else{H();}}function H(){var ag=o.length;if(ag>0){for(var af=0;af<ag;af++){var Y=o[af].id;var ab=o[af].callbackFn;var aa={success:false,id:Y};if(M.pv[0]>0){var ae=c(Y);
if(ae){if(F(o[af].swfVersion)&&!(M.wk&&M.wk<312)){w(Y,true);if(ab){aa.success=true;aa.ref=z(Y);ab(aa);}}else{if(o[af].expressInstall&&A()){var ai={};ai.data=o[af].expressInstall;
ai.width=ae.getAttribute("width")||"0";ai.height=ae.getAttribute("height")||"0";if(ae.getAttribute("class")){ai.styleclass=ae.getAttribute("class");}if(ae.getAttribute("align")){ai.align=ae.getAttribute("align");
}var ah={};var X=ae.getElementsByTagName("param");var ac=X.length;for(var ad=0;ad<ac;ad++){if(X[ad].getAttribute("name").toLowerCase()!="movie"){ah[X[ad].getAttribute("name")]=X[ad].getAttribute("value");
}}P(ai,ah,Y,ab);}else{p(ae);if(ab){ab(aa);}}}}}else{w(Y,true);if(ab){var Z=z(Y);if(Z&&typeof Z.SetVariable!=D){aa.success=true;aa.ref=Z;}ab(aa);}}}}}function z(aa){var X=null;
var Y=c(aa);if(Y&&Y.nodeName=="OBJECT"){if(typeof Y.SetVariable!=D){X=Y;}else{var Z=Y.getElementsByTagName(r)[0];if(Z){X=Z;}}}return X;}function A(){return !a&&F("6.0.65")&&(M.win||M.mac)&&!(M.wk&&M.wk<312);
}function P(aa,ab,X,Z){a=true;E=Z||null;B={success:false,id:X};var ae=c(X);if(ae){if(ae.nodeName=="OBJECT"){l=g(ae);Q=null;}else{l=ae;Q=X;}aa.id=R;if(typeof aa.width==D||(!/%$/.test(aa.width)&&parseInt(aa.width,10)<310)){aa.width="310";
}if(typeof aa.height==D||(!/%$/.test(aa.height)&&parseInt(aa.height,10)<137)){aa.height="137";}j.title=j.title.slice(0,47)+" - Flash Player Installation";
var ad=M.ie&&M.win?"ActiveX":"PlugIn",ac="MMredirectURL="+O.location.toString().replace(/&/g,"%26")+"&MMplayerType="+ad+"&MMdoctitle="+j.title;if(typeof ab.flashvars!=D){ab.flashvars+="&"+ac;
}else{ab.flashvars=ac;}if(M.ie&&M.win&&ae.readyState!=4){var Y=C("div");X+="SWFObjectNew";Y.setAttribute("id",X);ae.parentNode.insertBefore(Y,ae);ae.style.display="none";
(function(){if(ae.readyState==4){ae.parentNode.removeChild(ae);}else{setTimeout(arguments.callee,10);}})();}u(aa,ab,X);}}function p(Y){if(M.ie&&M.win&&Y.readyState!=4){var X=C("div");
Y.parentNode.insertBefore(X,Y);X.parentNode.replaceChild(g(Y),X);Y.style.display="none";(function(){if(Y.readyState==4){Y.parentNode.removeChild(Y);}else{setTimeout(arguments.callee,10);
}})();}else{Y.parentNode.replaceChild(g(Y),Y);}}function g(ab){var aa=C("div");if(M.win&&M.ie){aa.innerHTML=ab.innerHTML;}else{var Y=ab.getElementsByTagName(r)[0];
if(Y){var ad=Y.childNodes;if(ad){var X=ad.length;for(var Z=0;Z<X;Z++){if(!(ad[Z].nodeType==1&&ad[Z].nodeName=="PARAM")&&!(ad[Z].nodeType==8)){aa.appendChild(ad[Z].cloneNode(true));
}}}}}return aa;}function u(ai,ag,Y){var X,aa=c(Y);if(M.wk&&M.wk<312){return X;}if(aa){if(typeof ai.id==D){ai.id=Y;}if(M.ie&&M.win){var ah="";for(var ae in ai){if(ai[ae]!=Object.prototype[ae]){if(ae.toLowerCase()=="data"){ag.movie=ai[ae];
}else{if(ae.toLowerCase()=="styleclass"){ah+=' class="'+ai[ae]+'"';}else{if(ae.toLowerCase()!="classid"){ah+=" "+ae+'="'+ai[ae]+'"';}}}}}var af="";for(var ad in ag){if(ag[ad]!=Object.prototype[ad]){af+='<param name="'+ad+'" value="'+ag[ad]+'" />';
}}aa.outerHTML='<object classid="clsid:D27CDB6E-AE6D-11cf-96B8-444553540000"'+ah+">"+af+"</object>";N[N.length]=ai.id;X=c(ai.id);}else{var Z=C(r);Z.setAttribute("type",q);
for(var ac in ai){if(ai[ac]!=Object.prototype[ac]){if(ac.toLowerCase()=="styleclass"){Z.setAttribute("class",ai[ac]);}else{if(ac.toLowerCase()!="classid"){Z.setAttribute(ac,ai[ac]);
}}}}for(var ab in ag){if(ag[ab]!=Object.prototype[ab]&&ab.toLowerCase()!="movie"){e(Z,ab,ag[ab]);}}aa.parentNode.replaceChild(Z,aa);X=Z;}}return X;}function e(Z,X,Y){var aa=C("param");
aa.setAttribute("name",X);aa.setAttribute("value",Y);Z.appendChild(aa);}function y(Y){var X=c(Y);if(X&&X.nodeName=="OBJECT"){if(M.ie&&M.win){X.style.display="none";
(function(){if(X.readyState==4){b(Y);}else{setTimeout(arguments.callee,10);}})();}else{X.parentNode.removeChild(X);}}}function b(Z){var Y=c(Z);if(Y){for(var X in Y){if(typeof Y[X]=="function"){Y[X]=null;
}}Y.parentNode.removeChild(Y);}}function c(Z){var X=null;try{X=j.getElementById(Z);}catch(Y){}return X;}function C(X){return j.createElement(X);}function i(Z,X,Y){Z.attachEvent(X,Y);
I[I.length]=[Z,X,Y];}function F(Z){var Y=M.pv,X=Z.split(".");X[0]=parseInt(X[0],10);X[1]=parseInt(X[1],10)||0;X[2]=parseInt(X[2],10)||0;return(Y[0]>X[0]||(Y[0]==X[0]&&Y[1]>X[1])||(Y[0]==X[0]&&Y[1]==X[1]&&Y[2]>=X[2]))?true:false;
}function v(ac,Y,ad,ab){if(M.ie&&M.mac){return;}var aa=j.getElementsByTagName("head")[0];if(!aa){return;}var X=(ad&&typeof ad=="string")?ad:"screen";if(ab){n=null;
G=null;}if(!n||G!=X){var Z=C("style");Z.setAttribute("type","text/css");Z.setAttribute("media",X);n=aa.appendChild(Z);if(M.ie&&M.win&&typeof j.styleSheets!=D&&j.styleSheets.length>0){n=j.styleSheets[j.styleSheets.length-1];
}G=X;}if(M.ie&&M.win){if(n&&typeof n.addRule==r){n.addRule(ac,Y);}}else{if(n&&typeof j.createTextNode!=D){n.appendChild(j.createTextNode(ac+" {"+Y+"}"));
}}}function w(Z,X){if(!m){return;}var Y=X?"visible":"hidden";if(J&&c(Z)){c(Z).style.visibility=Y;}else{v("#"+Z,"visibility:"+Y);}}function L(Y){var Z=/[\\\"<>\.;]/;
var X=Z.exec(Y)!=null;return X&&typeof encodeURIComponent!=D?encodeURIComponent(Y):Y;}var d=function(){if(M.ie&&M.win){window.attachEvent("onunload",function(){var ac=I.length;
for(var ab=0;ab<ac;ab++){I[ab][0].detachEvent(I[ab][1],I[ab][2]);}var Z=N.length;for(var aa=0;aa<Z;aa++){y(N[aa]);}for(var Y in M){M[Y]=null;}M=null;for(var X in swfobject){swfobject[X]=null;
}swfobject=null;});}}();return{registerObject:function(ab,X,aa,Z){if(M.w3&&ab&&X){var Y={};Y.id=ab;Y.swfVersion=X;Y.expressInstall=aa;Y.callbackFn=Z;o[o.length]=Y;
w(ab,false);}else{if(Z){Z({success:false,id:ab});}}},getObjectById:function(X){if(M.w3){return z(X);}},embedSWF:function(ab,ah,ae,ag,Y,aa,Z,ad,af,ac){var X={success:false,id:ah};
if(M.w3&&!(M.wk&&M.wk<312)&&ab&&ah&&ae&&ag&&Y){w(ah,false);K(function(){ae+="";ag+="";var aj={};if(af&&typeof af===r){for(var al in af){aj[al]=af[al];}}aj.data=ab;
aj.width=ae;aj.height=ag;var am={};if(ad&&typeof ad===r){for(var ak in ad){am[ak]=ad[ak];}}if(Z&&typeof Z===r){for(var ai in Z){if(typeof am.flashvars!=D){am.flashvars+="&"+ai+"="+Z[ai];
}else{am.flashvars=ai+"="+Z[ai];}}}if(F(Y)){var an=u(aj,am,ah);if(aj.id==ah){w(ah,true);}X.success=true;X.ref=an;}else{if(aa&&A()){aj.data=aa;P(aj,am,ah,ac);
return;}else{w(ah,true);}}if(ac){ac(X);}});}else{if(ac){ac(X);}}},switchOffAutoHideShow:function(){m=false;},ua:M,getFlashPlayerVersion:function(){return{major:M.pv[0],minor:M.pv[1],release:M.pv[2]};
},hasFlashPlayerVersion:F,createSWF:function(Z,Y,X){if(M.w3){return u(Z,Y,X);}else{return undefined;}},showExpressInstall:function(Z,aa,X,Y){if(M.w3&&A()){P(Z,aa,X,Y);
}},removeSWF:function(X){if(M.w3){y(X);}},createCSS:function(aa,Z,Y,X){if(M.w3){v(aa,Z,Y,X);}},addDomLoadEvent:K,addLoadEvent:s,getQueryParamValue:function(aa){var Z=j.location.search||j.location.hash;
if(Z){if(/\?/.test(Z)){Z=Z.split("?")[1];}if(aa==null){return L(Z);}var Y=Z.split("&");for(var X=0;X<Y.length;X++){if(Y[X].substring(0,Y[X].indexOf("="))==aa){return L(Y[X].substring((Y[X].indexOf("=")+1)));
}}}return"";},expressInstallCallback:function(){if(a){var X=c(R);if(X&&l){X.parentNode.replaceChild(l,X);if(Q){w(Q,true);if(M.ie&&M.win){l.style.display="block";
}}if(E){E(B);}}a=false;}}};}();
/*
SWFUpload: http://www.swfupload.org, http://swfupload.googlecode.com
mmSWFUpload 1.0: Flash upload dialog - http://profandesign.se/swfupload/, http://www.vinterwebb.se/
SWFUpload is (c) 2006-2007 Lars Huring, Olov Nilzén and Mammon Media and is released under the MIT License:
http://www.opensource.org/licenses/mit-license.php
SWFUpload 2 is (c) 2007-2008 Jake Roberts and is released under the MIT License:
http://www.opensource.org/licenses/mit-license.php
*/
var SWFUpload;if(SWFUpload==undefined){SWFUpload=function(a){this.initSWFUpload(a)}}SWFUpload.prototype.initSWFUpload=function(b){try{this.customSettings={};this.settings=b;this.eventQueue=[];this.movieName="SWFUpload_"+SWFUpload.movieCount++;this.movieElement=null;SWFUpload.instances[this.movieName]=this;this.initSettings();this.loadFlash();this.displayDebugInfo()}catch(a){delete SWFUpload.instances[this.movieName];throw a}};SWFUpload.instances={};SWFUpload.movieCount=0;SWFUpload.version="2.2.0 2009-03-25";SWFUpload.QUEUE_ERROR={QUEUE_LIMIT_EXCEEDED:-100,FILE_EXCEEDS_SIZE_LIMIT:-110,ZERO_BYTE_FILE:-120,INVALID_FILETYPE:-130};SWFUpload.UPLOAD_ERROR={HTTP_ERROR:-200,MISSING_UPLOAD_URL:-210,IO_ERROR:-220,SECURITY_ERROR:-230,UPLOAD_LIMIT_EXCEEDED:-240,UPLOAD_FAILED:-250,SPECIFIED_FILE_ID_NOT_FOUND:-260,FILE_VALIDATION_FAILED:-270,FILE_CANCELLED:-280,UPLOAD_STOPPED:-290};SWFUpload.FILE_STATUS={QUEUED:-1,IN_PROGRESS:-2,ERROR:-3,COMPLETE:-4,CANCELLED:-5};SWFUpload.BUTTON_ACTION={SELECT_FILE:-100,SELECT_FILES:-110,START_UPLOAD:-120};SWFUpload.CURSOR={ARROW:-1,HAND:-2};SWFUpload.WINDOW_MODE={WINDOW:"window",TRANSPARENT:"transparent",OPAQUE:"opaque"};SWFUpload.completeURL=function(a){if(typeof(a)!=="string"||a.match(/^https?:\/\//i)||a.match(/^\//)){return a}var c=window.location.protocol+"//"+window.location.hostname+(window.location.port?":"+window.location.port:"");var b=window.location.pathname.lastIndexOf("/");if(b<=0){path="/"}else{path=window.location.pathname.substr(0,b)+"/"}return path+a};SWFUpload.prototype.initSettings=function(){this.ensureDefault=function(b,a){this.settings[b]=(this.settings[b]==undefined)?a:this.settings[b]};this.ensureDefault("upload_url","");this.ensureDefault("preserve_relative_urls",false);this.ensureDefault("file_post_name","Filedata");this.ensureDefault("post_params",{});this.ensureDefault("use_query_string",false);this.ensureDefault("requeue_on_error",false);this.ensureDefault("http_success",[]);this.ensureDefault("assume_success_timeout",0);this.ensureDefault("file_types","*.*");this.ensureDefault("file_types_description","All Files");this.ensureDefault("file_size_limit",0);this.ensureDefault("file_upload_limit",0);this.ensureDefault("file_queue_limit",0);this.ensureDefault("flash_url","swfupload.swf");this.ensureDefault("prevent_swf_caching",true);this.ensureDefault("button_image_url","");this.ensureDefault("button_width",1);this.ensureDefault("button_height",1);this.ensureDefault("button_text","");this.ensureDefault("button_text_style","color: #000000; font-size: 16pt;");this.ensureDefault("button_text_top_padding",0);this.ensureDefault("button_text_left_padding",0);this.ensureDefault("button_action",SWFUpload.BUTTON_ACTION.SELECT_FILES);this.ensureDefault("button_disabled",false);this.ensureDefault("button_placeholder_id","");this.ensureDefault("button_placeholder",null);this.ensureDefault("button_cursor",SWFUpload.CURSOR.ARROW);this.ensureDefault("button_window_mode",SWFUpload.WINDOW_MODE.WINDOW);this.ensureDefault("debug",false);this.settings.debug_enabled=this.settings.debug;this.settings.return_upload_start_handler=this.returnUploadStart;this.ensureDefault("swfupload_loaded_handler",null);this.ensureDefault("file_dialog_start_handler",null);this.ensureDefault("file_queued_handler",null);this.ensureDefault("file_queue_error_handler",null);this.ensureDefault("file_dialog_complete_handler",null);this.ensureDefault("upload_start_handler",null);this.ensureDefault("upload_progress_handler",null);this.ensureDefault("upload_error_handler",null);this.ensureDefault("upload_success_handler",null);this.ensureDefault("upload_complete_handler",null);this.ensureDefault("debug_handler",this.debugMessage);this.ensureDefault("custom_settings",{});this.customSettings=this.settings.custom_settings;if(!!this.settings.prevent_swf_caching){this.settings.flash_url=this.settings.flash_url+(this.settings.flash_url.indexOf("?")<0?"?":"&")+"preventswfcaching="+new Date().getTime()}if(!this.settings.preserve_relative_urls){this.settings.upload_url=SWFUpload.completeURL(this.settings.upload_url);this.settings.button_image_url=SWFUpload.completeURL(this.settings.button_image_url)}delete this.ensureDefault};SWFUpload.prototype.loadFlash=function(){var a,b;if(document.getElementById(this.movieName)!==null){throw"ID "+this.movieName+" is already in use. The Flash Object could not be added"}a=document.getElementById(this.settings.button_placeholder_id)||this.settings.button_placeholder;if(a==undefined){throw"Could not find the placeholder element: "+this.settings.button_placeholder_id}b=document.createElement("div");b.innerHTML=this.getFlashHTML();a.parentNode.replaceChild(b.firstChild,a);if(window[this.movieName]==undefined){window[this.movieName]=this.getMovieElement()}};SWFUpload.prototype.getFlashHTML=function(){return['<object id="',this.movieName,'" type="application/x-shockwave-flash" data="',this.settings.flash_url,'" width="',this.settings.button_width,'" height="',this.settings.button_height,'" class="swfupload">','<param name="wmode" value="',this.settings.button_window_mode,'" />','<param name="movie" value="',this.settings.flash_url,'" />','<param name="quality" value="high" />','<param name="menu" value="false" />','<param name="allowScriptAccess" value="always" />','<param name="flashvars" value="'+this.getFlashVars()+'" />',"</object>"].join("")};SWFUpload.prototype.getFlashVars=function(){var b=this.buildParamString();var a=this.settings.http_success.join(",");return["movieName=",encodeURIComponent(this.movieName),"&uploadURL=",encodeURIComponent(this.settings.upload_url),"&useQueryString=",encodeURIComponent(this.settings.use_query_string),"&requeueOnError=",encodeURIComponent(this.settings.requeue_on_error),"&httpSuccess=",encodeURIComponent(a),"&assumeSuccessTimeout=",encodeURIComponent(this.settings.assume_success_timeout),"&params=",encodeURIComponent(b),"&filePostName=",encodeURIComponent(this.settings.file_post_name),"&fileTypes=",encodeURIComponent(this.settings.file_types),"&fileTypesDescription=",encodeURIComponent(this.settings.file_types_description),"&fileSizeLimit=",encodeURIComponent(this.settings.file_size_limit),"&fileUploadLimit=",encodeURIComponent(this.settings.file_upload_limit),"&fileQueueLimit=",encodeURIComponent(this.settings.file_queue_limit),"&debugEnabled=",encodeURIComponent(this.settings.debug_enabled),"&buttonImageURL=",encodeURIComponent(this.settings.button_image_url),"&buttonWidth=",encodeURIComponent(this.settings.button_width),"&buttonHeight=",encodeURIComponent(this.settings.button_height),"&buttonText=",encodeURIComponent(this.settings.button_text),"&buttonTextTopPadding=",encodeURIComponent(this.settings.button_text_top_padding),"&buttonTextLeftPadding=",encodeURIComponent(this.settings.button_text_left_padding),"&buttonTextStyle=",encodeURIComponent(this.settings.button_text_style),"&buttonAction=",encodeURIComponent(this.settings.button_action),"&buttonDisabled=",encodeURIComponent(this.settings.button_disabled),"&buttonCursor=",encodeURIComponent(this.settings.button_cursor)].join("")};SWFUpload.prototype.getMovieElement=function(){if(this.movieElement==undefined){this.movieElement=document.getElementById(this.movieName)}if(this.movieElement===null){throw"Could not find Flash element"}return this.movieElement};SWFUpload.prototype.buildParamString=function(){var c=this.settings.post_params;var b=[];if(typeof(c)==="object"){for(var a in c){if(c.hasOwnProperty(a)){b.push(encodeURIComponent(a.toString())+"="+encodeURIComponent(c[a].toString()))}}}return b.join("&")};SWFUpload.prototype.destroy=function(){try{this.cancelUpload(null,false);var a=null;a=this.getMovieElement();if(a&&typeof(a.CallFunction)==="unknown"){for(var c in a){try{if(typeof(a[c])==="function"){a[c]=null}}catch(e){}}try{a.parentNode.removeChild(a)}catch(b){}}window[this.movieName]=null;SWFUpload.instances[this.movieName]=null;delete SWFUpload.instances[this.movieName];this.movieElement=null;this.settings=null;this.customSettings=null;this.eventQueue=null;this.movieName=null;return true}catch(d){return false}};SWFUpload.prototype.displayDebugInfo=function(){this.debug(["---SWFUpload Instance Info---\n","Version: ",SWFUpload.version,"\n","Movie Name: ",this.movieName,"\n","Settings:\n","\t","upload_url: ",this.settings.upload_url,"\n","\t","flash_url: ",this.settings.flash_url,"\n","\t","use_query_string: ",this.settings.use_query_string.toString(),"\n","\t","requeue_on_error: ",this.settings.requeue_on_error.toString(),"\n","\t","http_success: ",this.settings.http_success.join(", "),"\n","\t","assume_success_timeout: ",this.settings.assume_success_timeout,"\n","\t","file_post_name: ",this.settings.file_post_name,"\n","\t","post_params: ",this.settings.post_params.toString(),"\n","\t","file_types: ",this.settings.file_types,"\n","\t","file_types_description: ",this.settings.file_types_description,"\n","\t","file_size_limit: ",this.settings.file_size_limit,"\n","\t","file_upload_limit: ",this.settings.file_upload_limit,"\n","\t","file_queue_limit: ",this.settings.file_queue_limit,"\n","\t","debug: ",this.settings.debug.toString(),"\n","\t","prevent_swf_caching: ",this.settings.prevent_swf_caching.toString(),"\n","\t","button_placeholder_id: ",this.settings.button_placeholder_id.toString(),"\n","\t","button_placeholder: ",(this.settings.button_placeholder?"Set":"Not Set"),"\n","\t","button_image_url: ",this.settings.button_image_url.toString(),"\n","\t","button_width: ",this.settings.button_width.toString(),"\n","\t","button_height: ",this.settings.button_height.toString(),"\n","\t","button_text: ",this.settings.button_text.toString(),"\n","\t","button_text_style: ",this.settings.button_text_style.toString(),"\n","\t","button_text_top_padding: ",this.settings.button_text_top_padding.toString(),"\n","\t","button_text_left_padding: ",this.settings.button_text_left_padding.toString(),"\n","\t","button_action: ",this.settings.button_action.toString(),"\n","\t","button_disabled: ",this.settings.button_disabled.toString(),"\n","\t","custom_settings: ",this.settings.custom_settings.toString(),"\n","Event Handlers:\n","\t","swfupload_loaded_handler assigned: ",(typeof this.settings.swfupload_loaded_handler==="function").toString(),"\n","\t","file_dialog_start_handler assigned: ",(typeof this.settings.file_dialog_start_handler==="function").toString(),"\n","\t","file_queued_handler assigned: ",(typeof this.settings.file_queued_handler==="function").toString(),"\n","\t","file_queue_error_handler assigned: ",(typeof this.settings.file_queue_error_handler==="function").toString(),"\n","\t","upload_start_handler assigned: ",(typeof this.settings.upload_start_handler==="function").toString(),"\n","\t","upload_progress_handler assigned: ",(typeof this.settings.upload_progress_handler==="function").toString(),"\n","\t","upload_error_handler assigned: ",(typeof this.settings.upload_error_handler==="function").toString(),"\n","\t","upload_success_handler assigned: ",(typeof this.settings.upload_success_handler==="function").toString(),"\n","\t","upload_complete_handler assigned: ",(typeof this.settings.upload_complete_handler==="function").toString(),"\n","\t","debug_handler assigned: ",(typeof this.settings.debug_handler==="function").toString(),"\n"].join(""))};SWFUpload.prototype.addSetting=function(b,c,a){if(c==undefined){return(this.settings[b]=a)}else{return(this.settings[b]=c)}};SWFUpload.prototype.getSetting=function(a){if(this.settings[a]!=undefined){return this.settings[a]}return""};SWFUpload.prototype.callFlash=function(functionName,argumentArray){argumentArray=argumentArray||[];var movieElement=this.getMovieElement();var returnValue,returnString;try{returnString=movieElement.CallFunction('<invoke name="'+functionName+'" returntype="javascript">'+__flash__argumentsToXML(argumentArray,0)+"</invoke>");returnValue=eval(returnString)}catch(ex){throw"Call to "+functionName+" failed"}if(returnValue!=undefined&&typeof returnValue.post==="object"){returnValue=this.unescapeFilePostParams(returnValue)}return returnValue};SWFUpload.prototype.selectFile=function(){this.callFlash("SelectFile")};SWFUpload.prototype.selectFiles=function(){this.callFlash("SelectFiles")};SWFUpload.prototype.startUpload=function(a){this.callFlash("StartUpload",[a])};SWFUpload.prototype.cancelUpload=function(a,b){if(b!==false){b=true}this.callFlash("CancelUpload",[a,b])};SWFUpload.prototype.stopUpload=function(){this.callFlash("StopUpload")};SWFUpload.prototype.getStats=function(){return this.callFlash("GetStats")};SWFUpload.prototype.setStats=function(a){this.callFlash("SetStats",[a])};SWFUpload.prototype.getFile=function(a){if(typeof(a)==="number"){return this.callFlash("GetFileByIndex",[a])}else{return this.callFlash("GetFile",[a])}};SWFUpload.prototype.addFileParam=function(a,b,c){return this.callFlash("AddFileParam",[a,b,c])};SWFUpload.prototype.removeFileParam=function(a,b){this.callFlash("RemoveFileParam",[a,b])};SWFUpload.prototype.setUploadURL=function(a){this.settings.upload_url=a.toString();this.callFlash("SetUploadURL",[a])};SWFUpload.prototype.setPostParams=function(a){this.settings.post_params=a;this.callFlash("SetPostParams",[a])};SWFUpload.prototype.addPostParam=function(a,b){this.settings.post_params[a]=b;this.callFlash("SetPostParams",[this.settings.post_params])};SWFUpload.prototype.removePostParam=function(a){delete this.settings.post_params[a];this.callFlash("SetPostParams",[this.settings.post_params])};SWFUpload.prototype.setFileTypes=function(a,b){this.settings.file_types=a;this.settings.file_types_description=b;this.callFlash("SetFileTypes",[a,b])};SWFUpload.prototype.setFileSizeLimit=function(a){this.settings.file_size_limit=a;this.callFlash("SetFileSizeLimit",[a])};SWFUpload.prototype.setFileUploadLimit=function(a){this.settings.file_upload_limit=a;this.callFlash("SetFileUploadLimit",[a])};SWFUpload.prototype.setFileQueueLimit=function(a){this.settings.file_queue_limit=a;this.callFlash("SetFileQueueLimit",[a])};SWFUpload.prototype.setFilePostName=function(a){this.settings.file_post_name=a;this.callFlash("SetFilePostName",[a])};SWFUpload.prototype.setUseQueryString=function(a){this.settings.use_query_string=a;this.callFlash("SetUseQueryString",[a])};SWFUpload.prototype.setRequeueOnError=function(a){this.settings.requeue_on_error=a;this.callFlash("SetRequeueOnError",[a])};SWFUpload.prototype.setHTTPSuccess=function(a){if(typeof a==="string"){a=a.replace(" ","").split(",")}this.settings.http_success=a;this.callFlash("SetHTTPSuccess",[a])};SWFUpload.prototype.setAssumeSuccessTimeout=function(a){this.settings.assume_success_timeout=a;this.callFlash("SetAssumeSuccessTimeout",[a])};SWFUpload.prototype.setDebugEnabled=function(a){this.settings.debug_enabled=a;this.callFlash("SetDebugEnabled",[a])};SWFUpload.prototype.setButtonImageURL=function(a){if(a==undefined){a=""}this.settings.button_image_url=a;this.callFlash("SetButtonImageURL",[a])};SWFUpload.prototype.setButtonDimensions=function(c,a){this.settings.button_width=c;this.settings.button_height=a;var b=this.getMovieElement();if(b!=undefined){b.style.width=c+"px";b.style.height=a+"px"}this.callFlash("SetButtonDimensions",[c,a])};SWFUpload.prototype.setButtonText=function(a){this.settings.button_text=a;this.callFlash("SetButtonText",[a])};SWFUpload.prototype.setButtonTextPadding=function(b,a){this.settings.button_text_top_padding=a;this.settings.button_text_left_padding=b;this.callFlash("SetButtonTextPadding",[b,a])};SWFUpload.prototype.setButtonTextStyle=function(a){this.settings.button_text_style=a;this.callFlash("SetButtonTextStyle",[a])};SWFUpload.prototype.setButtonDisabled=function(a){this.settings.button_disabled=a;this.callFlash("SetButtonDisabled",[a])};SWFUpload.prototype.setButtonAction=function(a){this.settings.button_action=a;this.callFlash("SetButtonAction",[a])};SWFUpload.prototype.setButtonCursor=function(a){this.settings.button_cursor=a;this.callFlash("SetButtonCursor",[a])};SWFUpload.prototype.queueEvent=function(b,c){if(c==undefined){c=[]}else{if(!(c instanceof Array)){c=[c]}}var a=this;if(typeof this.settings[b]==="function"){this.eventQueue.push(function(){this.settings[b].apply(this,c)});setTimeout(function(){a.executeNextEvent()},0)}else{if(this.settings[b]!==null){throw"Event handler "+b+" is unknown or is not a function"}}};SWFUpload.prototype.executeNextEvent=function(){var a=this.eventQueue?this.eventQueue.shift():null;if(typeof(a)==="function"){a.apply(this)}};SWFUpload.prototype.unescapeFilePostParams=function(c){var e=/[$]([0-9a-f]{4})/i;var f={};var d;if(c!=undefined){for(var a in c.post){if(c.post.hasOwnProperty(a)){d=a;var b;while((b=e.exec(d))!==null){d=d.replace(b[0],String.fromCharCode(parseInt("0x"+b[1],16)))}f[d]=c.post[a]}}c.post=f}return c};SWFUpload.prototype.testExternalInterface=function(){try{return this.callFlash("TestExternalInterface")}catch(a){return false}};SWFUpload.prototype.flashReady=function(){var a=this.getMovieElement();if(!a){this.debug("Flash called back ready but the flash movie can't be found.");return}this.cleanUp(a);this.queueEvent("swfupload_loaded_handler")};SWFUpload.prototype.cleanUp=function(a){try{if(this.movieElement&&typeof(a.CallFunction)==="unknown"){this.debug("Removing Flash functions hooks (this should only run in IE and should prevent memory leaks)");for(var c in a){try{if(typeof(a[c])==="function"){a[c]=null}}catch(b){}}}}catch(d){}window.__flash__removeCallback=function(e,f){try{if(e){e[f]=null}}catch(g){}}};SWFUpload.prototype.fileDialogStart=function(){this.queueEvent("file_dialog_start_handler")};SWFUpload.prototype.fileQueued=function(a){a=this.unescapeFilePostParams(a);this.queueEvent("file_queued_handler",a)};SWFUpload.prototype.fileQueueError=function(a,c,b){a=this.unescapeFilePostParams(a);this.queueEvent("file_queue_error_handler",[a,c,b])};SWFUpload.prototype.fileDialogComplete=function(b,c,a){this.queueEvent("file_dialog_complete_handler",[b,c,a])};SWFUpload.prototype.uploadStart=function(a){a=this.unescapeFilePostParams(a);this.queueEvent("return_upload_start_handler",a)};SWFUpload.prototype.returnUploadStart=function(a){var b;if(typeof this.settings.upload_start_handler==="function"){a=this.unescapeFilePostParams(a);b=this.settings.upload_start_handler.call(this,a)}else{if(this.settings.upload_start_handler!=undefined){throw"upload_start_handler must be a function"}}if(b===undefined){b=true}b=!!b;this.callFlash("ReturnUploadStart",[b])};SWFUpload.prototype.uploadProgress=function(a,c,b){a=this.unescapeFilePostParams(a);this.queueEvent("upload_progress_handler",[a,c,b])};SWFUpload.prototype.uploadError=function(a,c,b){a=this.unescapeFilePostParams(a);this.queueEvent("upload_error_handler",[a,c,b])};SWFUpload.prototype.uploadSuccess=function(b,a,c){b=this.unescapeFilePostParams(b);this.queueEvent("upload_success_handler",[b,a,c])};SWFUpload.prototype.uploadComplete=function(a){a=this.unescapeFilePostParams(a);this.queueEvent("upload_complete_handler",a)};SWFUpload.prototype.debug=function(a){this.queueEvent("debug_handler",a)};SWFUpload.prototype.debugMessage=function(c){if(this.settings.debug){var a,d=[];if(typeof c==="object"&&typeof c.name==="string"&&typeof c.message==="string"){for(var b in c){if(c.hasOwnProperty(b)){d.push(b+": "+c[b])}}a=d.join("\n")||"";d=a.split("\n");a="EXCEPTION: "+d.join("\nEXCEPTION: ");SWFUpload.Console.writeLine(a)}else{SWFUpload.Console.writeLine(c)}}};SWFUpload.Console={};SWFUpload.Console.writeLine=function(d){var b,a;try{b=document.getElementById("SWFUpload_Console");if(!b){a=document.createElement("form");document.getElementsByTagName("body")[0].appendChild(a);b=document.createElement("textarea");b.id="SWFUpload_Console";b.style.fontFamily="monospace";b.setAttribute("wrap","off");b.wrap="off";b.style.overflow="auto";b.style.width="700px";b.style.height="350px";b.style.margin="5px";a.appendChild(b)}b.value+=d+"\n";b.scrollTop=b.scrollHeight-b.clientHeight}catch(c){alert("Exception: "+c.name+" Message: "+c.message)}};
/*
Uploadify v3.2
Copyright (c) 2012 Reactive Apps, Ronnie Garcia
Released under the MIT License <http://www.opensource.org/licenses/mit-license.php>
*/
(function($) {
// These methods can be called by adding them as the first argument in the uploadify plugin call
var methods = {
init : function(options, swfUploadOptions) {
return this.each(function() {
// Create a reference to the jQuery DOM object
var $this = $(this);
// Clone the original DOM object
var $clone = $this.clone();
// Setup the default options
var settings = $.extend({
// Required Settings
id : $this.attr('id'), // The ID of the DOM object
swf : 'uploadify.swf', // The path to the uploadify SWF file
uploader : 'uploadify.php', // The path to the server-side upload script
// Options
auto : true, // Automatically upload files when added to the queue
buttonClass : '', // A class name to add to the browse button DOM object
buttonCursor : 'hand', // The cursor to use with the browse button
buttonImage : null, // (String or null) The path to an image to use for the Flash browse button if not using CSS to style the button
buttonText : 'SELECT FILES', // The text to use for the browse button
checkExisting : false, // The path to a server-side script that checks for existing files on the server
debug : false, // Turn on swfUpload debugging mode
fileObjName : 'Filedata', // The name of the file object to use in your server-side script
fileSizeLimit : 0, // The maximum size of an uploadable file in KB (Accepts units B KB MB GB if string, 0 for no limit)
fileTypeDesc : 'All Files', // The description for file types in the browse dialog
fileTypeExts : '*.*', // Allowed extensions in the browse dialog (server-side validation should also be used)
height : 30, // The height of the browse button
itemTemplate : false, // The template for the file item in the queue
method : 'post', // The method to use when sending files to the server-side upload script
multi : true, // Allow multiple file selection in the browse dialog
formData : {}, // An object with additional data to send to the server-side upload script with every file upload
preventCaching : true, // Adds a random value to the Flash URL to prevent caching of it (conflicts with existing parameters)
progressData : 'percentage', // ('percentage' or 'speed') Data to show in the queue item during a file upload
queueID : false, // The ID of the DOM object to use as a file queue (without the #)
queueSizeLimit : 999, // The maximum number of files that can be in the queue at one time
removeCompleted : true, // Remove queue items from the queue when they are done uploading
removeTimeout : 3, // The delay in seconds before removing a queue item if removeCompleted is set to true
requeueErrors : false, // Keep errored files in the queue and keep trying to upload them
successTimeout : 30, // The number of seconds to wait for Flash to detect the server's response after the file has finished uploading
uploadLimit : 0, // The maximum number of files you can upload
width : 120, // The width of the browse button
// Events
overrideEvents : [] // (Array) A list of default event handlers to skip
/*
onCancel // Triggered when a file is cancelled from the queue
onClearQueue // Triggered during the 'clear queue' method
onDestroy // Triggered when the uploadify object is destroyed
onDialogClose // Triggered when the browse dialog is closed
onDialogOpen // Triggered when the browse dialog is opened
onDisable // Triggered when the browse button gets disabled
onEnable // Triggered when the browse button gets enabled
onFallback // Triggered is Flash is not detected
onInit // Triggered when Uploadify is initialized
onQueueComplete // Triggered when all files in the queue have been uploaded
onSelectError // Triggered when an error occurs while selecting a file (file size, queue size limit, etc.)
onSelect // Triggered for each file that is selected
onSWFReady // Triggered when the SWF button is loaded
onUploadComplete // Triggered when a file upload completes (success or error)
onUploadError // Triggered when a file upload returns an error
onUploadSuccess // Triggered when a file is uploaded successfully
onUploadProgress // Triggered every time a file progress is updated
onUploadStart // Triggered immediately before a file upload starts
*/
}, options);
// Prepare settings for SWFUpload
var swfUploadSettings = {
assume_success_timeout : settings.successTimeout,
button_placeholder_id : settings.id,
button_width : settings.width,
button_height : settings.height,
button_text : null,
button_text_style : null,
button_text_top_padding : 0,
button_text_left_padding : 0,
button_action : (settings.multi ? SWFUpload.BUTTON_ACTION.SELECT_FILES : SWFUpload.BUTTON_ACTION.SELECT_FILE),
button_disabled : false,
button_cursor : (settings.buttonCursor == 'arrow' ? SWFUpload.CURSOR.ARROW : SWFUpload.CURSOR.HAND),
button_window_mode : SWFUpload.WINDOW_MODE.TRANSPARENT,
debug : settings.debug,
requeue_on_error : settings.requeueErrors,
file_post_name : settings.fileObjName,
file_size_limit : settings.fileSizeLimit,
file_types : settings.fileTypeExts,
file_types_description : settings.fileTypeDesc,
file_queue_limit : settings.queueSizeLimit,
file_upload_limit : settings.uploadLimit,
flash_url : settings.swf,
prevent_swf_caching : settings.preventCaching,
post_params : settings.formData,
upload_url : settings.uploader,
use_query_string : (settings.method == 'get'),
// Event Handlers
file_dialog_complete_handler : handlers.onDialogClose,
file_dialog_start_handler : handlers.onDialogOpen,
file_queued_handler : handlers.onSelect,
file_queue_error_handler : handlers.onSelectError,
swfupload_loaded_handler : settings.onSWFReady,
upload_complete_handler : handlers.onUploadComplete,
upload_error_handler : handlers.onUploadError,
upload_progress_handler : handlers.onUploadProgress,
upload_start_handler : handlers.onUploadStart,
upload_success_handler : handlers.onUploadSuccess
}
// Merge the user-defined options with the defaults
if (swfUploadOptions) {
swfUploadSettings = $.extend(swfUploadSettings, swfUploadOptions);
}
// Add the user-defined settings to the swfupload object
swfUploadSettings = $.extend(swfUploadSettings, settings);
// Detect if Flash is available
var playerVersion = swfobject.getFlashPlayerVersion();
var flashInstalled = (playerVersion.major >= 9);
if (flashInstalled) {
// Create the swfUpload instance
window['uploadify_' + settings.id] = new SWFUpload(swfUploadSettings);
var swfuploadify = window['uploadify_' + settings.id];
// Add the SWFUpload object to the elements data object
$this.data('uploadify', swfuploadify);
// Wrap the instance
var $wrapper = $('<div />', {
'id' : settings.id,
'class' : 'uploadify',
'css' : {
'height' : settings.height + 'px',
'width' : settings.width + 'px'
}
});
$('#' + swfuploadify.movieName).wrap($wrapper);
// Recreate the reference to wrapper
$wrapper = $('#' + settings.id);
// Add the data object to the wrapper
$wrapper.data('uploadify', swfuploadify);
// Create the button
var $button = $('<div />', {
'id' : settings.id + '-button',
'class' : 'uploadify-button ' + settings.buttonClass
});
if (settings.buttonImage) {
$button.css({
'background-image' : "url('" + settings.buttonImage + "')",
'text-indent' : '-9999px'
});
}
$button.html('<span class="uploadify-button-text">' + settings.buttonText + '</span>')
.css({
'height' : settings.height + 'px',
'line-height' : settings.height + 'px',
'width' : settings.width + 'px'
});
// Append the button to the wrapper
$wrapper.append($button);
// Adjust the styles of the movie
$('#' + swfuploadify.movieName).css({
'position' : 'absolute',
'z-index' : 2000
});
// Create the file queue
if (!settings.queueID) {
var $queue = $('<div />', {
'id' : settings.id + '-queue',
'class' : 'uploadify-queue'
});
$wrapper.after($queue);
swfuploadify.settings.queueID = settings.id + '-queue';
swfuploadify.settings.defaultQueue = true;
}
// Create some queue related objects and variables
swfuploadify.queueData = {
files : {}, // The files in the queue
filesSelected : 0, // The number of files selected in the last select operation
filesQueued : 0, // The number of files added to the queue in the last select operation
filesReplaced : 0, // The number of files replaced in the last select operation
filesCancelled : 0, // The number of files that were cancelled instead of replaced
filesErrored : 0, // The number of files that caused error in the last select operation
uploadsSuccessful : 0, // The number of files that were successfully uploaded
uploadsErrored : 0, // The number of files that returned errors during upload
averageSpeed : 0, // The average speed of the uploads in KB
queueLength : 0, // The number of files in the queue
queueSize : 0, // The size in bytes of the entire queue
uploadSize : 0, // The size in bytes of the upload queue
queueBytesUploaded : 0, // The size in bytes that have been uploaded for the current upload queue
uploadQueue : [], // The files currently to be uploaded
errorMsg : 'Some files were not added to the queue:'
};
// Save references to all the objects
swfuploadify.original = $clone;
swfuploadify.wrapper = $wrapper;
swfuploadify.button = $button;
swfuploadify.queue = $queue;
// Call the user-defined init event handler
if (settings.onInit) settings.onInit.call($this, swfuploadify);
} else {
// Call the fallback function
if (settings.onFallback) settings.onFallback.call($this);
}
});
},
// Stop a file upload and remove it from the queue
cancel : function(fileID, supressEvent) {
var args = arguments;
this.each(function() {
// Create a reference to the jQuery DOM object
var $this = $(this),
swfuploadify = $this.data('uploadify'),
settings = swfuploadify.settings,
delay = -1;
if (args[0]) {
// Clear the queue
if (args[0] == '*') {
var queueItemCount = swfuploadify.queueData.queueLength;
$('#' + settings.queueID).find('.uploadify-queue-item').each(function() {
delay++;
if (args[1] === true) {
swfuploadify.cancelUpload($(this).attr('id'), false);
} else {
swfuploadify.cancelUpload($(this).attr('id'));
}
$(this).find('.data').removeClass('data').html(' - Cancelled');
$(this).find('.uploadify-progress-bar').remove();
$(this).delay(1000 + 100 * delay).fadeOut(500, function() {
$(this).remove();
});
});
swfuploadify.queueData.queueSize = 0;
swfuploadify.queueData.queueLength = 0;
// Trigger the onClearQueue event
if (settings.onClearQueue) settings.onClearQueue.call($this, queueItemCount);
} else {
for (var n = 0; n < args.length; n++) {
swfuploadify.cancelUpload(args[n]);
$('#' + args[n]).find('.data').removeClass('data').html(' - Cancelled');
$('#' + args[n]).find('.uploadify-progress-bar').remove();
$('#' + args[n]).delay(1000 + 100 * n).fadeOut(500, function() {
$(this).remove();
});
}
}
} else {
var item = $('#' + settings.queueID).find('.uploadify-queue-item').get(0);
$item = $(item);
swfuploadify.cancelUpload($item.attr('id'));
$item.find('.data').removeClass('data').html(' - Cancelled');
$item.find('.uploadify-progress-bar').remove();
$item.delay(1000).fadeOut(500, function() {
$(this).remove();
});
}
});
},
// Revert the DOM object back to its original state
destroy : function() {
this.each(function() {
// Create a reference to the jQuery DOM object
var $this = $(this),
swfuploadify = $this.data('uploadify'),
settings = swfuploadify.settings;
// Destroy the SWF object and
swfuploadify.destroy();
// Destroy the queue
if (settings.defaultQueue) {
$('#' + settings.queueID).remove();
}
// Reload the original DOM element
$('#' + settings.id).replaceWith(swfuploadify.original);
// Call the user-defined event handler
if (settings.onDestroy) settings.onDestroy.call(this);
delete swfuploadify;
});
},
// Disable the select button
disable : function(isDisabled) {
this.each(function() {
// Create a reference to the jQuery DOM object
var $this = $(this),
swfuploadify = $this.data('uploadify'),
settings = swfuploadify.settings;
// Call the user-defined event handlers
if (isDisabled) {
swfuploadify.button.addClass('disabled');
if (settings.onDisable) settings.onDisable.call(this);
} else {
swfuploadify.button.removeClass('disabled');
if (settings.onEnable) settings.onEnable.call(this);
}
// Enable/disable the browse button
swfuploadify.setButtonDisabled(isDisabled);
});
},
// Get or set the settings data
settings : function(name, value, resetObjects) {
var args = arguments;
var returnValue = value;
this.each(function() {
// Create a reference to the jQuery DOM object
var $this = $(this),
swfuploadify = $this.data('uploadify'),
settings = swfuploadify.settings;
if (typeof(args[0]) == 'object') {
for (var n in value) {
setData(n,value[n]);
}
}
if (args.length === 1) {
returnValue = settings[name];
} else {
switch (name) {
case 'uploader':
swfuploadify.setUploadURL(value);
break;
case 'formData':
if (!resetObjects) {
value = $.extend(settings.formData, value);
}
swfuploadify.setPostParams(settings.formData);
break;
case 'method':
if (value == 'get') {
swfuploadify.setUseQueryString(true);
} else {
swfuploadify.setUseQueryString(false);
}
break;
case 'fileObjName':
swfuploadify.setFilePostName(value);
break;
case 'fileTypeExts':
swfuploadify.setFileTypes(value, settings.fileTypeDesc);
break;
case 'fileTypeDesc':
swfuploadify.setFileTypes(settings.fileTypeExts, value);
break;
case 'fileSizeLimit':
swfuploadify.setFileSizeLimit(value);
break;
case 'uploadLimit':
swfuploadify.setFileUploadLimit(value);
break;
case 'queueSizeLimit':
swfuploadify.setFileQueueLimit(value);
break;
case 'buttonImage':
swfuploadify.button.css('background-image', settingValue);
break;
case 'buttonCursor':
if (value == 'arrow') {
swfuploadify.setButtonCursor(SWFUpload.CURSOR.ARROW);
} else {
swfuploadify.setButtonCursor(SWFUpload.CURSOR.HAND);
}
break;
case 'buttonText':
$('#' + settings.id + '-button').find('.uploadify-button-text').html(value);
break;
case 'width':
swfuploadify.setButtonDimensions(value, settings.height);
break;
case 'height':
swfuploadify.setButtonDimensions(settings.width, value);
break;
case 'multi':
if (value) {
swfuploadify.setButtonAction(SWFUpload.BUTTON_ACTION.SELECT_FILES);
} else {
swfuploadify.setButtonAction(SWFUpload.BUTTON_ACTION.SELECT_FILE);
}
break;
}
settings[name] = value;
}
});
if (args.length === 1) {
return returnValue;
}
},
// Stop the current uploads and requeue what is in progress
stop : function() {
this.each(function() {
// Create a reference to the jQuery DOM object
var $this = $(this),
swfuploadify = $this.data('uploadify');
// Reset the queue information
swfuploadify.queueData.averageSpeed = 0;
swfuploadify.queueData.uploadSize = 0;
swfuploadify.queueData.bytesUploaded = 0;
swfuploadify.queueData.uploadQueue = [];
swfuploadify.stopUpload();
});
},
// Start uploading files in the queue
upload : function() {
var args = arguments;
this.each(function() {
// Create a reference to the jQuery DOM object
var $this = $(this),
swfuploadify = $this.data('uploadify');
// Reset the queue information
swfuploadify.queueData.averageSpeed = 0;
swfuploadify.queueData.uploadSize = 0;
swfuploadify.queueData.bytesUploaded = 0;
swfuploadify.queueData.uploadQueue = [];
// Upload the files
if (args[0]) {
if (args[0] == '*') {
swfuploadify.queueData.uploadSize = swfuploadify.queueData.queueSize;
swfuploadify.queueData.uploadQueue.push('*');
swfuploadify.startUpload();
} else {
for (var n = 0; n < args.length; n++) {
swfuploadify.queueData.uploadSize += swfuploadify.queueData.files[args[n]].size;
swfuploadify.queueData.uploadQueue.push(args[n]);
}
swfuploadify.startUpload(swfuploadify.queueData.uploadQueue.shift());
}
} else {
swfuploadify.startUpload();
}
});
}
}
// These functions handle all the events that occur with the file uploader
var handlers = {
// Triggered when the file dialog is opened
onDialogOpen : function() {
// Load the swfupload settings
var settings = this.settings;
// Reset some queue info
this.queueData.errorMsg = 'Some files were not added to the queue:';
this.queueData.filesReplaced = 0;
this.queueData.filesCancelled = 0;
// Call the user-defined event handler
if (settings.onDialogOpen) settings.onDialogOpen.call(this);
},
// Triggered when the browse dialog is closed
onDialogClose : function(filesSelected, filesQueued, queueLength) {
// Load the swfupload settings
var settings = this.settings;
// Update the queue information
this.queueData.filesErrored = filesSelected - filesQueued;
this.queueData.filesSelected = filesSelected;
this.queueData.filesQueued = filesQueued - this.queueData.filesCancelled;
this.queueData.queueLength = queueLength;
// Run the default event handler
if ($.inArray('onDialogClose', settings.overrideEvents) < 0) {
if (this.queueData.filesErrored > 0) {
alert(this.queueData.errorMsg);
}
}
// Call the user-defined event handler
if (settings.onDialogClose) settings.onDialogClose.call(this, this.queueData);
// Upload the files if auto is true
if (settings.auto) $('#' + settings.id).uploadify('upload', '*');
},
// Triggered once for each file added to the queue
onSelect : function(file) {
// Load the swfupload settings
var settings = this.settings;
// Check if a file with the same name exists in the queue
var queuedFile = {};
for (var n in this.queueData.files) {
queuedFile = this.queueData.files[n];
if (queuedFile.uploaded != true && queuedFile.name == file.name) {
var replaceQueueItem = confirm('The file named "' + file.name + '" is already in the queue.\nDo you want to replace the existing item in the queue?');
if (!replaceQueueItem) {
this.cancelUpload(file.id);
this.queueData.filesCancelled++;
return false;
} else {
$('#' + queuedFile.id).remove();
this.cancelUpload(queuedFile.id);
this.queueData.filesReplaced++;
}
}
}
// Get the size of the file
var fileSize = Math.round(file.size / 1024);
var suffix = 'KB';
if (fileSize > 1000) {
fileSize = Math.round(fileSize / 1000);
suffix = 'MB';
}
var fileSizeParts = fileSize.toString().split('.');
fileSize = fileSizeParts[0];
if (fileSizeParts.length > 1) {
fileSize += '.' + fileSizeParts[1].substr(0,2);
}
fileSize += suffix;
// Truncate the filename if it's too long
var fileName = file.name;
if (fileName.length > 25) {
fileName = fileName.substr(0,25) + '...';
}
// Create the file data object
itemData = {
'fileID' : file.id,
'instanceID' : settings.id,
'fileName' : fileName,
'fileSize' : fileSize
}
// Create the file item template
if (settings.itemTemplate == false) {
settings.itemTemplate = '<div id="${fileID}" class="uploadify-queue-item">\
<div class="cancel">\
<a href="javascript:$(\'#${instanceID}\').uploadify(\'cancel\', \'${fileID}\')">X</a>\
</div>\
<span class="fileName">${fileName} (${fileSize})</span><span class="data"></span>\
<div class="uploadify-progress">\
<div class="uploadify-progress-bar"><!--Progress Bar--></div>\
</div>\
</div>';
}
// Run the default event handler
if ($.inArray('onSelect', settings.overrideEvents) < 0) {
// Replace the item data in the template
itemHTML = settings.itemTemplate;
for (var d in itemData) {
itemHTML = itemHTML.replace(new RegExp('\\$\\{' + d + '\\}', 'g'), itemData[d]);
}
// Add the file item to the queue
$('#' + settings.queueID).append(itemHTML);
}
this.queueData.queueSize += file.size;
this.queueData.files[file.id] = file;
// Call the user-defined event handler
if (settings.onSelect) settings.onSelect.apply(this, arguments);
},
// Triggered when a file is not added to the queue
onSelectError : function(file, errorCode, errorMsg) {
// Load the swfupload settings
var settings = this.settings;
// Run the default event handler
if ($.inArray('onSelectError', settings.overrideEvents) < 0) {
switch(errorCode) {
case SWFUpload.QUEUE_ERROR.QUEUE_LIMIT_EXCEEDED:
if (settings.queueSizeLimit > errorMsg) {
this.queueData.errorMsg += '\nThe number of files selected exceeds the remaining upload limit (' + errorMsg + ').';
} else {
this.queueData.errorMsg += '\nThe number of files selected exceeds the queue size limit (' + settings.queueSizeLimit + ').';
}
break;
case SWFUpload.QUEUE_ERROR.FILE_EXCEEDS_SIZE_LIMIT:
this.queueData.errorMsg += '\nThe file "' + file.name + '" exceeds the size limit (' + settings.fileSizeLimit + ').';
break;
case SWFUpload.QUEUE_ERROR.ZERO_BYTE_FILE:
this.queueData.errorMsg += '\nThe file "' + file.name + '" is empty.';
break;
case SWFUpload.QUEUE_ERROR.FILE_EXCEEDS_SIZE_LIMIT:
this.queueData.errorMsg += '\nThe file "' + file.name + '" is not an accepted file type (' + settings.fileTypeDesc + ').';
break;
}
}
if (errorCode != SWFUpload.QUEUE_ERROR.QUEUE_LIMIT_EXCEEDED) {
delete this.queueData.files[file.id];
}
// Call the user-defined event handler
if (settings.onSelectError) settings.onSelectError.apply(this, arguments);
},
// Triggered when all the files in the queue have been processed
onQueueComplete : function() {
if (this.settings.onQueueComplete) this.settings.onQueueComplete.call(this, this.settings.queueData);
},
// Triggered when a file upload successfully completes
onUploadComplete : function(file) {
// Load the swfupload settings
var settings = this.settings,
swfuploadify = this;
// Check if all the files have completed uploading
var stats = this.getStats();
this.queueData.queueLength = stats.files_queued;
if (this.queueData.uploadQueue[0] == '*') {
if (this.queueData.queueLength > 0) {
this.startUpload();
} else {
this.queueData.uploadQueue = [];
// Call the user-defined event handler for queue complete
if (settings.onQueueComplete) settings.onQueueComplete.call(this, this.queueData);
}
} else {
if (this.queueData.uploadQueue.length > 0) {
this.startUpload(this.queueData.uploadQueue.shift());
} else {
this.queueData.uploadQueue = [];
// Call the user-defined event handler for queue complete
if (settings.onQueueComplete) settings.onQueueComplete.call(this, this.queueData);
}
}
// Call the default event handler
if ($.inArray('onUploadComplete', settings.overrideEvents) < 0) {
if (settings.removeCompleted) {
switch (file.filestatus) {
case SWFUpload.FILE_STATUS.COMPLETE:
setTimeout(function() {
if ($('#' + file.id)) {
swfuploadify.queueData.queueSize -= file.size;
swfuploadify.queueData.queueLength -= 1;
delete swfuploadify.queueData.files[file.id]
$('#' + file.id).fadeOut(500, function() {
$(this).remove();
});
}
}, settings.removeTimeout * 1000);
break;
case SWFUpload.FILE_STATUS.ERROR:
if (!settings.requeueErrors) {
setTimeout(function() {
if ($('#' + file.id)) {
swfuploadify.queueData.queueSize -= file.size;
swfuploadify.queueData.queueLength -= 1;
delete swfuploadify.queueData.files[file.id];
$('#' + file.id).fadeOut(500, function() {
$(this).remove();
});
}
}, settings.removeTimeout * 1000);
}
break;
}
} else {
file.uploaded = true;
}
}
// Call the user-defined event handler
if (settings.onUploadComplete) settings.onUploadComplete.call(this, file);
},
// Triggered when a file upload returns an error
onUploadError : function(file, errorCode, errorMsg) {
// Load the swfupload settings
var settings = this.settings;
// Set the error string
var errorString = 'Error';
switch(errorCode) {
case SWFUpload.UPLOAD_ERROR.HTTP_ERROR:
errorString = 'HTTP Error (' + errorMsg + ')';
break;
case SWFUpload.UPLOAD_ERROR.MISSING_UPLOAD_URL:
errorString = 'Missing Upload URL';
break;
case SWFUpload.UPLOAD_ERROR.IO_ERROR:
errorString = 'IO Error';
break;
case SWFUpload.UPLOAD_ERROR.SECURITY_ERROR:
errorString = 'Security Error';
break;
case SWFUpload.UPLOAD_ERROR.UPLOAD_LIMIT_EXCEEDED:
alert('The upload limit has been reached (' + errorMsg + ').');
errorString = 'Exceeds Upload Limit';
break;
case SWFUpload.UPLOAD_ERROR.UPLOAD_FAILED:
errorString = 'Failed';
break;
case SWFUpload.UPLOAD_ERROR.SPECIFIED_FILE_ID_NOT_FOUND:
break;
case SWFUpload.UPLOAD_ERROR.FILE_VALIDATION_FAILED:
errorString = 'Validation Error';
break;
case SWFUpload.UPLOAD_ERROR.FILE_CANCELLED:
errorString = 'Cancelled';
this.queueData.queueSize -= file.size;
this.queueData.queueLength -= 1;
if (file.status == SWFUpload.FILE_STATUS.IN_PROGRESS || $.inArray(file.id, this.queueData.uploadQueue) >= 0) {
this.queueData.uploadSize -= file.size;
}
// Trigger the onCancel event
if (settings.onCancel) settings.onCancel.call(this, file);
delete this.queueData.files[file.id];
break;
case SWFUpload.UPLOAD_ERROR.UPLOAD_STOPPED:
errorString = 'Stopped';
break;
}
// Call the default event handler
if ($.inArray('onUploadError', settings.overrideEvents) < 0) {
if (errorCode != SWFUpload.UPLOAD_ERROR.FILE_CANCELLED && errorCode != SWFUpload.UPLOAD_ERROR.UPLOAD_STOPPED) {
$('#' + file.id).addClass('uploadify-error');
}
// Reset the progress bar
$('#' + file.id).find('.uploadify-progress-bar').css('width','1px');
// Add the error message to the queue item
if (errorCode != SWFUpload.UPLOAD_ERROR.SPECIFIED_FILE_ID_NOT_FOUND && file.status != SWFUpload.FILE_STATUS.COMPLETE) {
$('#' + file.id).find('.data').html(' - ' + errorString);
}
}
var stats = this.getStats();
this.queueData.uploadsErrored = stats.upload_errors;
// Call the user-defined event handler
if (settings.onUploadError) settings.onUploadError.call(this, file, errorCode, errorMsg, errorString);
},
// Triggered periodically during a file upload
onUploadProgress : function(file, fileBytesLoaded, fileTotalBytes) {
// Load the swfupload settings
var settings = this.settings;
// Setup all the variables
var timer = new Date();
var newTime = timer.getTime();
var lapsedTime = newTime - this.timer;
if (lapsedTime > 500) {
this.timer = newTime;
}
var lapsedBytes = fileBytesLoaded - this.bytesLoaded;
this.bytesLoaded = fileBytesLoaded;
var queueBytesLoaded = this.queueData.queueBytesUploaded + fileBytesLoaded;
var percentage = Math.round(fileBytesLoaded / fileTotalBytes * 100);
// Calculate the average speed
var suffix = 'KB/s';
var mbs = 0;
var kbs = (lapsedBytes / 1024) / (lapsedTime / 1000);
kbs = Math.floor(kbs * 10) / 10;
if (this.queueData.averageSpeed > 0) {
this.queueData.averageSpeed = Math.floor((this.queueData.averageSpeed + kbs) / 2);
} else {
this.queueData.averageSpeed = Math.floor(kbs);
}
if (kbs > 1000) {
mbs = (kbs * .001);
this.queueData.averageSpeed = Math.floor(mbs);
suffix = 'MB/s';
}
// Call the default event handler
if ($.inArray('onUploadProgress', settings.overrideEvents) < 0) {
if (settings.progressData == 'percentage') {
$('#' + file.id).find('.data').html(' - ' + percentage + '%');
} else if (settings.progressData == 'speed' && lapsedTime > 500) {
$('#' + file.id).find('.data').html(' - ' + this.queueData.averageSpeed + suffix);
}
$('#' + file.id).find('.uploadify-progress-bar').css('width', percentage + '%');
}
// Call the user-defined event handler
if (settings.onUploadProgress) settings.onUploadProgress.call(this, file, fileBytesLoaded, fileTotalBytes, queueBytesLoaded, this.queueData.uploadSize);
},
// Triggered right before a file is uploaded
onUploadStart : function(file) {
// Load the swfupload settings
var settings = this.settings;
var timer = new Date();
this.timer = timer.getTime();
this.bytesLoaded = 0;
if (this.queueData.uploadQueue.length == 0) {
this.queueData.uploadSize = file.size;
}
if (settings.checkExisting) {
$.ajax({
type : 'POST',
async : false,
url : settings.checkExisting,
data : {filename: file.name},
success : function(data) {
if (data == 1) {
var overwrite = confirm('A file with the name "' + file.name + '" already exists on the server.\nWould you like to replace the existing file?');
if (!overwrite) {
this.cancelUpload(file.id);
$('#' + file.id).remove();
if (this.queueData.uploadQueue.length > 0 && this.queueData.queueLength > 0) {
if (this.queueData.uploadQueue[0] == '*') {
this.startUpload();
} else {
this.startUpload(this.queueData.uploadQueue.shift());
}
}
}
}
}
});
}
// Call the user-defined event handler
if (settings.onUploadStart) settings.onUploadStart.call(this, file);
},
// Triggered when a file upload returns a successful code
onUploadSuccess : function(file, data, response) {
// Load the swfupload settings
var settings = this.settings;
var stats = this.getStats();
this.queueData.uploadsSuccessful = stats.successful_uploads;
this.queueData.queueBytesUploaded += file.size;
// Call the default event handler
if ($.inArray('onUploadSuccess', settings.overrideEvents) < 0) {
$('#' + file.id).find('.data').html(' - Complete');
}
// Call the user-defined event handler
if (settings.onUploadSuccess) settings.onUploadSuccess.call(this, file, data, response);
}
}
$.fn.uploadify = function(method) {
if (methods[method]) {
return methods[method].apply(this, Array.prototype.slice.call(arguments, 1));
} else if (typeof method === 'object' || !method) {
return methods.init.apply(this, arguments);
} else {
$.error('The method ' + method + ' does not exist in $.uploadify');
}
}
})($); | JavaScript |
$(document).ready(function() {
if($('div.form.login').length) { // in login page
$('input#LoginForm_password').focus();
}
$('table.preview input[name="checkAll"]').click(function() {
$('table.preview .confirm input').prop('checked', this.checked);
});
$('table.preview td.confirm input').click(function() {
$('table.preview input[name="checkAll"]').prop('checked', !$('table.preview td.confirm input:not(:checked)').length);
});
$('table.preview input[name="checkAll"]').prop('checked', !$('table.preview td.confirm input:not(:checked)').length);
$('.form .row.sticky input:not(.error), .form .row.sticky select:not(.error), .form .row.sticky textarea:not(.error)').each(function(){
var value;
if(this.tagName=='SELECT')
value=this.options[this.selectedIndex].text;
else if(this.tagName=='TEXTAREA')
value=$(this).html();
else
value=$(this).val();
if(value=='')
value='[empty]';
$(this).before('<div class="value">'+value+'</div>').hide();
});
$(document).on('click', '.form.gii .row.sticky .value', function(){
$(this).hide();
$(this).next().show().get(0).focus();
});
$('.form.gii .row input, .form.gii .row textarea, .form.gii .row select, .with-tooltip').not('.no-tooltip, .no-tooltip *').tooltip({
position: "center right",
offset: [-2, 10]
});
$('.form.gii .row input').change(function(){
$('.form.gii .feedback').hide();
$('.form.gii input[name="generate"]').hide();
});
$('.form.gii .view-code').click(function(){
var title=$(this).attr('rel');
$.fancybox.showActivity();
$.ajax({
type: 'POST',
cache: false,
url: $(this).attr('href'),
data: $('.form.gii form').serializeArray(),
success: function(data){
$.fancybox(data, {
'title': title,
'titlePosition': 'inside',
'titleFormat': function(title, currentArray, currentIndex, currentOpts) {
return '<div id="tip7-title"><span><a href="javascript:;" onclick="$.fancybox.close();">close</a></span>' + (title && title.length ? '<b>' + title + '</b>' : '' ) + '</div>';
},
'showCloseButton': false,
'autoDimensions': false,
'width': 900,
'height': 'auto',
'onComplete':function(){
$('#fancybox-inner').scrollTop(0);
}
});
},
error: function(XMLHttpRequest, textStatus, errorThrown) {
$.fancybox('<div class="error">'+XMLHttpRequest.responseText+'</div>');
}
});
return false;
});
$(document).on('click', '#fancybox-inner .close-code', function(){
$.fancybox.close();
return false;
});
}); | JavaScript |
/**
* jQuery Yii ListView plugin file.
*
* @author Qiang Xue <qiang.xue@gmail.com>
* @link http://www.yiiframework.com/
* @copyright Copyright © 2008-2010 Yii Software LLC
* @license http://www.yiiframework.com/license/
*/
;(function($) {
/**
* yiiListView set function.
* @param options map settings for the list view. Availablel options are as follows:
* - ajaxUpdate: array, IDs of the containers whose content may be updated by ajax response
* - ajaxVar: string, the name of the GET variable indicating the ID of the element triggering the AJAX request
* - pagerClass: string, the CSS class for the pager container
* - sorterClass: string, the CSS class for the sorter container
* - updateSelector: string, the selector for choosing which elements can trigger ajax requests
* - beforeAjaxUpdate: function, the function to be called before ajax request is sent
* - afterAjaxUpdate: function, the function to be called after ajax response is received
*/
$.fn.yiiListView = function(options) {
return this.each(function(){
var settings = $.extend({}, $.fn.yiiListView.defaults, options || {}),
$this = $(this),
id = $this.attr('id');
if(settings.updateSelector == undefined) {
settings.updateSelector = '#'+id+' .'+settings.pagerClass.replace(/\s+/g,'.')+' a, #'+id+' .'+settings.sorterClass.replace(/\s+/g,'.')+' a';
}
$.fn.yiiListView.settings[id] = settings;
if(settings.ajaxUpdate.length > 0) {
$(document).on('click.yiiListView', settings.updateSelector,function(){
if(settings.enableHistory && window.History.enabled) {
var url = $(this).attr('href').split('?'),
params = $.deparam.querystring('?'+url[1]);
delete params[settings.ajaxVar];
window.History.pushState(null, document.title, decodeURIComponent($.param.querystring(url[0], params)));
} else {
$.fn.yiiListView.update(id, {url: $(this).attr('href')});
}
return false;
});
if(settings.enableHistory && window.History.enabled) {
$(window).bind('statechange', function() { // Note: We are using statechange instead of popstate
var State = window.History.getState(); // Note: We are using History.getState() instead of event.state
$.fn.yiiListView.update(id, {url: State.url});
});
}
}
});
};
$.fn.yiiListView.defaults = {
ajaxUpdate: [],
ajaxVar: 'ajax',
pagerClass: 'pager',
loadingClass: 'loading',
sorterClass: 'sorter'
// updateSelector: '#id .pager a, '#id .sort a',
// beforeAjaxUpdate: function(id) {},
// afterAjaxUpdate: function(id, data) {},
// url: 'ajax request URL'
};
$.fn.yiiListView.settings = {};
/**
* Returns the key value for the specified row
* @param id string the ID of the list view container
* @param index integer the zero-based index of the data item
* @return string the key value
*/
$.fn.yiiListView.getKey = function(id, index) {
return $('#'+id+' > div.keys > span:eq('+index+')').text();
};
/**
* Returns the URL that generates the list view content.
* @param id string the ID of the list view container
* @return string the URL that generates the list view content.
*/
$.fn.yiiListView.getUrl = function(id) {
var settings = $.fn.yiiListView.settings[id];
return settings.url || $('#'+id+' > div.keys').attr('title');
};
/**
* Performs an AJAX-based update of the list view contents.
* @param id string the ID of the list view container
* @param options map the AJAX request options (see jQuery.ajax API manual). By default,
* the URL to be requested is the one that generates the current content of the list view.
*/
$.fn.yiiListView.update = function(id, options) {
var customError,
settings = $.fn.yiiListView.settings[id];
if (options && options.error !== undefined) {
customError = options.error;
delete options.error;
}
$('#'+id).addClass(settings.loadingClass);
options = $.extend({
type: 'GET',
url: $.fn.yiiListView.getUrl(id),
success: function(data,status) {
$.each(settings.ajaxUpdate, function(i,v) {
var id='#'+v;
$(id).replaceWith($(id,'<div>'+data+'</div>'));
});
if(settings.afterAjaxUpdate != undefined)
settings.afterAjaxUpdate(id, data);
$('#'+id).removeClass(settings.loadingClass);
},
error: function(XHR, textStatus, errorThrown) {
var ret, err;
$('#'+id).removeClass(settings.loadingClass);
if (XHR.readyState === 0 || XHR.status === 0) {
return;
}
if (customError !== undefined) {
ret = customError(XHR);
if (ret !== undefined && !ret) {
return;
}
}
switch (textStatus) {
case 'timeout':
err = 'The request timed out!';
break;
case 'parsererror':
err = 'Parser error!';
break;
case 'error':
if (XHR.status && !/^\s*$/.test(XHR.status)) {
err = 'Error ' + XHR.status;
} else {
err = 'Error';
}
if (XHR.responseText && !/^\s*$/.test(XHR.responseText)) {
err = err + ': ' + XHR.responseText;
}
break;
}
if (settings.ajaxUpdateError !== undefined) {
settings.ajaxUpdateError(XHR, textStatus, errorThrown, err);
} else if (err) {
alert(err);
}
}
}, options || {});
if(options.data!=undefined && options.type=='GET') {
options.url = $.param.querystring(options.url, options.data);
options.data = {};
}
options.url = $.param.querystring(options.url, settings.ajaxVar+'='+id);
if(settings.beforeAjaxUpdate != undefined)
settings.beforeAjaxUpdate(id);
$.ajax(options);
};
})(jQuery); | JavaScript |
/**
* jQuery Yii GridView plugin file.
*
* @author Qiang Xue <qiang.xue@gmail.com>
* @link http://www.yiiframework.com/
* @copyright Copyright © 2008-2010 Yii Software LLC
* @license http://www.yiiframework.com/license/
*/
(function ($) {
var selectCheckedRows, methods,
gridSettings = [];
/**
* 1. Selects rows that have checkbox checked (only checkbox that is connected with selecting a row)
* 2. Check if "check all" need to be checked/unchecked
* @return object the jQuery object
*/
selectCheckedRows = function (gridId) {
var settings = gridSettings[gridId],
table = $('#' + gridId).children('.' + settings.tableClass);
table.children('tbody').find('input.select-on-check').filter(':checked').each(function () {
$(this).closest('tr').addClass('selected');
});
table.children('thead').find('th input').filter('[type="checkbox"]').each(function () {
var name = this.name.substring(0, this.name.length - 4) + '[]', //.. remove '_all' and add '[]''
$checks = $("input[name='" + name + "']", table);
this.checked = $checks.length > 0 && $checks.length === $checks.filter(':checked').length;
});
return this;
};
methods = {
/**
* yiiGridView set function.
* @param options map settings for the grid view. Available options are as follows:
* - ajaxUpdate: array, IDs of the containers whose content may be updated by ajax response
* - ajaxVar: string, the name of the GET variable indicating the ID of the element triggering the AJAX request
* - pagerClass: string, the CSS class for the pager container
* - tableClass: string, the CSS class for the table
* - selectableRows: integer, the number of rows that can be selected
* - updateSelector: string, the selector for choosing which elements can trigger ajax requests
* - beforeAjaxUpdate: function, the function to be called before ajax request is sent
* - afterAjaxUpdate: function, the function to be called after ajax response is received
* - ajaxUpdateError: function, the function to be called if an ajax error occurs
* - selectionChanged: function, the function to be called after the row selection is changed
* @return object the jQuery object
*/
init: function (options) {
var settings = $.extend({
ajaxUpdate: [],
ajaxVar: 'ajax',
pagerClass: 'pager',
loadingClass: 'loading',
filterClass: 'filters',
tableClass: 'items',
selectableRows: 1
// updateSelector: '#id .pager a, '#id .grid thead th a',
// beforeAjaxUpdate: function (id) {},
// afterAjaxUpdate: function (id, data) {},
// selectionChanged: function (id) {},
// url: 'ajax request URL'
}, options || {});
settings.tableClass = settings.tableClass.replace(/\s+/g, '.');
return this.each(function () {
var eventType,
$grid = $(this),
id = $grid.attr('id'),
pagerSelector = '#' + id + ' .' + settings.pagerClass.replace(/\s+/g, '.') + ' a',
sortSelector = '#' + id + ' .' + settings.tableClass + ' thead th a.sort-link',
inputSelector = '#' + id + ' .' + settings.filterClass + ' input, ' + '#' + id + ' .' + settings.filterClass + ' select';
settings.updateSelector = settings.updateSelector
.replace('{page}', pagerSelector)
.replace('{sort}', sortSelector);
settings.filterSelector = settings.filterSelector
.replace('{filter}', inputSelector);
gridSettings[id] = settings;
if (settings.ajaxUpdate.length > 0) {
$(document).on('click.yiiGridView', settings.updateSelector, function () {
// Check to see if History.js is enabled for our Browser
if (settings.enableHistory && window.History.enabled) {
// Ajaxify this link
var url = $(this).attr('href').split('?'),
params = $.deparam.querystring('?'+url[1]);
delete params[settings.ajaxVar];
window.History.pushState(null, document.title, decodeURIComponent($.param.querystring(url[0], params)));
} else {
$('#' + id).yiiGridView('update', {url: $(this).attr('href')});
}
return false;
});
}
$(document).on('change.yiiGridView keydown.yiiGridView', settings.filterSelector, function (event) {
if (event.type === 'keydown') {
if( event.keyCode !== 13) {
return; // only react to enter key
} else {
eventType = 'keydown';
}
} else {
// prevent processing for both keydown and change events
if (eventType === 'keydown') {
eventType = '';
return;
}
}
var data = $(settings.filterSelector).serialize();
if (settings.pageVar !== undefined) {
data += '&' + settings.pageVar + '=1';
}
if (settings.enableHistory && settings.ajaxUpdate !== false && window.History.enabled) {
// Ajaxify this link
var url = $('#' + id).yiiGridView('getUrl'),
params = $.deparam.querystring($.param.querystring(url, data));
delete params[settings.ajaxVar];
window.History.pushState(null, document.title, decodeURIComponent($.param.querystring(url.substr(0, url.indexOf('?')), params)));
} else {
$('#' + id).yiiGridView('update', {data: data});
}
});
if (settings.enableHistory && settings.ajaxUpdate !== false && window.History.enabled) {
$(window).bind('statechange', function() { // Note: We are using statechange instead of popstate
var State = window.History.getState(); // Note: We are using History.getState() instead of event.state
$('#' + id).yiiGridView('update', {url: State.url});
});
}
if (settings.selectableRows > 0) {
selectCheckedRows(this.id);
$(document).on('click.yiiGridView', '#' + id + ' .' + settings.tableClass + ' > tbody > tr', function (e) {
var $currentGrid, $row, isRowSelected, $checks,
$target = $(e.target);
if ($target.closest('td').is('.empty,.button-column') || (e.target.type === 'checkbox' && !$target.hasClass('select-on-check'))) {
return;
}
$row = $(this);
$currentGrid = $('#' + id);
$checks = $('input.select-on-check', $currentGrid);
isRowSelected = $row.toggleClass('selected').hasClass('selected');
if (settings.selectableRows === 1) {
$row.siblings().removeClass('selected');
$checks.prop('checked', false);
}
$('input.select-on-check', $row).prop('checked', isRowSelected);
$("input.select-on-check-all", $currentGrid).prop('checked', $checks.length === $checks.filter(':checked').length);
if (settings.selectionChanged !== undefined) {
settings.selectionChanged(id);
}
});
if (settings.selectableRows > 1) {
$(document).on('click.yiiGridView', '#' + id + ' .select-on-check-all', function () {
var $currentGrid = $('#' + id),
$checks = $('input.select-on-check', $currentGrid),
$checksAll = $('input.select-on-check-all', $currentGrid),
$rows = $currentGrid.children('.' + settings.tableClass).children('tbody').children();
if (this.checked) {
$rows.addClass('selected');
$checks.prop('checked', true);
$checksAll.prop('checked', true);
} else {
$rows.removeClass('selected');
$checks.prop('checked', false);
$checksAll.prop('checked', false);
}
if (settings.selectionChanged !== undefined) {
settings.selectionChanged(id);
}
});
}
} else {
$(document).on('click.yiiGridView', '#' + id + ' .select-on-check', false);
}
});
},
/**
* Returns the key value for the specified row
* @param row integer the row number (zero-based index)
* @return string the key value
*/
getKey: function (row) {
return this.children('.keys').children('span').eq(row).text();
},
/**
* Returns the URL that generates the grid view content.
* @return string the URL that generates the grid view content.
*/
getUrl: function () {
var sUrl = gridSettings[this.attr('id')].url;
return sUrl || this.children('.keys').attr('title');
},
/**
* Returns the jQuery collection of the cells in the specified row.
* @param row integer the row number (zero-based index)
* @return jQuery the jQuery collection of the cells in the specified row.
*/
getRow: function (row) {
var sClass = gridSettings[this.attr('id')].tableClass;
return this.children('.' + sClass).children('tbody').children('tr').eq(row).children();
},
/**
* Returns the jQuery collection of the cells in the specified column.
* @param column integer the column number (zero-based index)
* @return jQuery the jQuery collection of the cells in the specified column.
*/
getColumn: function (column) {
var sClass = gridSettings[this.attr('id')].tableClass;
return this.children('.' + sClass).children('tbody').children('tr').children('td:nth-child(' + (column + 1) + ')');
},
/**
* Performs an AJAX-based update of the grid view contents.
* @param options map the AJAX request options (see jQuery.ajax API manual). By default,
* the URL to be requested is the one that generates the current content of the grid view.
* @return object the jQuery object
*/
update: function (options) {
var customError;
if (options && options.error !== undefined) {
customError = options.error;
delete options.error;
}
return this.each(function () {
var $form,
$grid = $(this),
id = $grid.attr('id'),
settings = gridSettings[id];
$grid.addClass(settings.loadingClass);
options = $.extend({
type: 'GET',
url: $grid.yiiGridView('getUrl'),
success: function (data) {
var $data = $('<div>' + data + '</div>');
$grid.removeClass(settings.loadingClass);
$.each(settings.ajaxUpdate, function (i, el) {
var updateId = '#' + el;
$(updateId).replaceWith($(updateId, $data));
});
if (settings.afterAjaxUpdate !== undefined) {
settings.afterAjaxUpdate(id, data);
}
if (settings.selectableRows > 0) {
selectCheckedRows(id);
}
},
error: function (XHR, textStatus, errorThrown) {
var ret, err;
$grid.removeClass(settings.loadingClass);
if (XHR.readyState === 0 || XHR.status === 0) {
return;
}
if (customError !== undefined) {
ret = customError(XHR);
if (ret !== undefined && !ret) {
return;
}
}
switch (textStatus) {
case 'timeout':
err = 'The request timed out!';
break;
case 'parsererror':
err = 'Parser error!';
break;
case 'error':
if (XHR.status && !/^\s*$/.test(XHR.status)) {
err = 'Error ' + XHR.status;
} else {
err = 'Error';
}
if (XHR.responseText && !/^\s*$/.test(XHR.responseText)) {
err = err + ': ' + XHR.responseText;
}
break;
}
if (settings.ajaxUpdateError !== undefined) {
settings.ajaxUpdateError(XHR, textStatus, errorThrown, err);
} else if (err) {
alert(err);
}
}
}, options || {});
if (options.data !== undefined && options.type === 'GET') {
options.url = $.param.querystring(options.url, options.data);
options.data = {};
}
if (settings.ajaxUpdate !== false) {
options.url = $.param.querystring(options.url, settings.ajaxVar + '=' + id);
if (settings.beforeAjaxUpdate !== undefined) {
settings.beforeAjaxUpdate(id, options);
}
$.ajax(options);
} else { // non-ajax mode
if (options.type === 'GET') {
window.location.href = options.url;
} else { // POST mode
$form = $('<form action="' + options.url + '" method="post"></form>').appendTo('body');
if (options.data === undefined) {
options.data = {};
}
if (options.data.returnUrl === undefined) {
options.data.returnUrl = window.location.href;
}
$.each(options.data, function (name, value) {
$form.append($('<input type="hidden" name="t" value="" />').attr('name', name).val(value));
});
$form.submit();
}
}
});
},
/**
* Returns the key values of the currently selected rows.
* @return array the key values of the currently selected rows.
*/
getSelection: function () {
var settings = gridSettings[this.attr('id')],
keys = this.find('.keys span'),
selection = [];
this.find('.' + settings.tableClass).children('tbody').children().each(function (i) {
if ($(this).hasClass('selected')) {
selection.push(keys.eq(i).text());
}
});
return selection;
},
/**
* Returns the key values of the currently checked rows.
* @param column_id string the ID of the column
* @return array the key values of the currently checked rows.
*/
getChecked: function (column_id) {
var settings = gridSettings[this.attr('id')],
keys = this.find('.keys span'),
checked = [];
if (column_id.substring(column_id.length - 2) !== '[]') {
column_id = column_id + '[]';
}
this.find('.' + settings.tableClass).children('tbody').children('tr').children('td').children('input[name="' + column_id + '"]').each(function (i) {
if (this.checked) {
checked.push(keys.eq(i).text());
}
});
return checked;
}
};
$.fn.yiiGridView = function (method) {
if (methods[method]) {
return methods[method].apply(this, Array.prototype.slice.call(arguments, 1));
} else if (typeof method === 'object' || !method) {
return methods.init.apply(this, arguments);
} else {
$.error('Method ' + method + ' does not exist on jQuery.yiiGridView');
return false;
}
};
/******************************************************************************
*** DEPRECATED METHODS
*** used before Yii 1.1.9
******************************************************************************/
$.fn.yiiGridView.settings = gridSettings;
/**
* Returns the key value for the specified row
* @param id string the ID of the grid view container
* @param row integer the row number (zero-based index)
* @return string the key value
*/
$.fn.yiiGridView.getKey = function (id, row) {
return $('#' + id).yiiGridView('getKey', row);
};
/**
* Returns the URL that generates the grid view content.
* @param id string the ID of the grid view container
* @return string the URL that generates the grid view content.
*/
$.fn.yiiGridView.getUrl = function (id) {
return $('#' + id).yiiGridView('getUrl');
};
/**
* Returns the jQuery collection of the cells in the specified row.
* @param id string the ID of the grid view container
* @param row integer the row number (zero-based index)
* @return jQuery the jQuery collection of the cells in the specified row.
*/
$.fn.yiiGridView.getRow = function (id, row) {
return $('#' + id).yiiGridView('getRow', row);
};
/**
* Returns the jQuery collection of the cells in the specified column.
* @param id string the ID of the grid view container
* @param column integer the column number (zero-based index)
* @return jQuery the jQuery collection of the cells in the specified column.
*/
$.fn.yiiGridView.getColumn = function (id, column) {
return $('#' + id).yiiGridView('getColumn', column);
};
/**
* Performs an AJAX-based update of the grid view contents.
* @param id string the ID of the grid view container
* @param options map the AJAX request options (see jQuery.ajax API manual). By default,
* the URL to be requested is the one that generates the current content of the grid view.
*/
$.fn.yiiGridView.update = function (id, options) {
$('#' + id).yiiGridView('update', options);
};
/**
* Returns the key values of the currently selected rows.
* @param id string the ID of the grid view container
* @return array the key values of the currently selected rows.
*/
$.fn.yiiGridView.getSelection = function (id) {
return $('#' + id).yiiGridView('getSelection');
};
/**
* Returns the key values of the currently checked rows.
* @param id string the ID of the grid view container
* @param column_id string the ID of the column
* @return array the key values of the currently checked rows.
*/
$.fn.yiiGridView.getChecked = function (id, column_id) {
return $('#' + id).yiiGridView('getChecked', column_id);
};
})(jQuery); | JavaScript |
/**
* jQuery Yii plugin file.
*
* @author Qiang Xue <qiang.xue@gmail.com>
* @link http://www.yiiframework.com/
* @copyright Copyright © 2008-2010 Yii Software LLC
* @license http://www.yiiframework.com/license/
*/
;(function($) {
$.yii = {
version : '1.0',
submitForm : function (element, url, params) {
var f = $(element).parents('form')[0];
if (!f) {
f = document.createElement('form');
f.style.display = 'none';
element.parentNode.appendChild(f);
f.method = 'POST';
}
if (typeof url == 'string' && url != '') {
f.action = url;
}
if (element.target != null) {
f.target = element.target;
}
var inputs = [];
$.each(params, function(name, value) {
var input = document.createElement("input");
input.setAttribute("type", "hidden");
input.setAttribute("name", name);
input.setAttribute("value", value);
f.appendChild(input);
inputs.push(input);
});
// remember who triggers the form submission
// this is used by jquery.yiiactiveform.js
$(f).data('submitObject', $(element));
$(f).trigger('submit');
$.each(inputs, function() {
f.removeChild(this);
});
}
};
})(jQuery);
| JavaScript |
/*
### jQuery Star Rating Plugin v3.14 - 2012-01-26 ###
* Home: http://www.fyneworks.com/jquery/star-rating/
* Code: http://code.google.com/p/jquery-star-rating-plugin/
*
* Dual licensed under the MIT and GPL licenses:
* http://www.opensource.org/licenses/mit-license.php
* http://www.gnu.org/licenses/gpl.html
###
*/
/*# AVOID COLLISIONS #*/
;if(window.jQuery) (function($){
/*# AVOID COLLISIONS #*/
// IE6 Background Image Fix
if ($.browser.msie) try { document.execCommand("BackgroundImageCache", false, true)} catch(e) { };
// Thanks to http://www.visualjquery.com/rating/rating_redux.html
// plugin initialization
$.fn.rating = function(options){
if(this.length==0) return this; // quick fail
// Handle API methods
if(typeof arguments[0]=='string'){
// Perform API methods on individual elements
if(this.length>1){
var args = arguments;
return this.each(function(){
$.fn.rating.apply($(this), args);
});
};
// Invoke API method handler
$.fn.rating[arguments[0]].apply(this, $.makeArray(arguments).slice(1) || []);
// Quick exit...
return this;
};
// Initialize options for this call
var options = $.extend(
{}/* new object */,
$.fn.rating.options/* default options */,
options || {} /* just-in-time options */
);
// Allow multiple controls with the same name by making each call unique
$.fn.rating.calls++;
// loop through each matched element
this
.not('.star-rating-applied')
.addClass('star-rating-applied')
.each(function(){
// Load control parameters / find context / etc
var control, input = $(this);
var eid = (this.name || 'unnamed-rating').replace(/\[|\]/g, '_').replace(/^\_+|\_+$/g,'');
var context = $(this.form || document.body);
// FIX: http://code.google.com/p/jquery-star-rating-plugin/issues/detail?id=23
var raters = context.data('rating');
if(!raters || raters.call!=$.fn.rating.calls) raters = { count:0, call:$.fn.rating.calls };
var rater = raters[eid];
// if rater is available, verify that the control still exists
if(rater) control = rater.data('rating');
if(rater && control)//{// save a byte!
// add star to control if rater is available and the same control still exists
control.count++;
//}// save a byte!
else{
// create new control if first star or control element was removed/replaced
// Initialize options for this rater
control = $.extend(
{}/* new object */,
options || {} /* current call options */,
($.metadata? input.metadata(): ($.meta?input.data():null)) || {}, /* metadata options */
{ count:0, stars: [], inputs: [] }
);
// increment number of rating controls
control.serial = raters.count++;
// create rating element
rater = $('<span class="star-rating-control"/>');
input.before(rater);
// Mark element for initialization (once all stars are ready)
rater.addClass('rating-to-be-drawn');
// Accept readOnly setting from 'disabled' property
if(input.attr('disabled') || input.hasClass('disabled')) control.readOnly = true;
// Accept required setting from class property (class='required')
if(input.hasClass('required')) control.required = true;
// Create 'cancel' button
rater.append(
control.cancel = $('<div class="rating-cancel"><a title="' + control.cancel + '">' + control.cancelValue + '</a></div>')
.mouseover(function(){
$(this).rating('drain');
$(this).addClass('star-rating-hover');
//$(this).rating('focus');
})
.mouseout(function(){
$(this).rating('draw');
$(this).removeClass('star-rating-hover');
//$(this).rating('blur');
})
.click(function(){
$(this).rating('select');
})
.data('rating', control)
);
}; // first element of group
// insert rating star
var star = $('<div class="star-rating rater-'+ control.serial +'"><a title="' + (this.title || this.value) + '">' + this.value + '</a></div>');
rater.append(star);
// inherit attributes from input element
if(this.id) star.attr('id', this.id);
if(this.className) star.addClass(this.className);
// Half-stars?
if(control.half) control.split = 2;
// Prepare division control
if(typeof control.split=='number' && control.split>0){
var stw = ($.fn.width ? star.width() : 0) || control.starWidth;
var spi = (control.count % control.split), spw = Math.floor(stw/control.split);
star
// restrict star's width and hide overflow (already in CSS)
.width(spw)
// move the star left by using a negative margin
// this is work-around to IE's stupid box model (position:relative doesn't work)
.find('a').css({ 'margin-left':'-'+ (spi*spw) +'px' })
};
// readOnly?
if(control.readOnly)//{ //save a byte!
// Mark star as readOnly so user can customize display
star.addClass('star-rating-readonly');
//} //save a byte!
else//{ //save a byte!
// Enable hover css effects
star.addClass('star-rating-live')
// Attach mouse events
.mouseover(function(){
$(this).rating('fill');
$(this).rating('focus');
})
.mouseout(function(){
$(this).rating('draw');
$(this).rating('blur');
})
.click(function(){
$(this).rating('select');
})
;
//}; //save a byte!
// set current selection
if(this.checked) control.current = star;
// set current select for links
if(this.nodeName=="A"){
if($(this).hasClass('selected'))
control.current = star;
};
// hide input element
input.hide();
// backward compatibility, form element to plugin
input.change(function(){
$(this).rating('select');
});
// attach reference to star to input element and vice-versa
star.data('rating.input', input.data('rating.star', star));
// store control information in form (or body when form not available)
control.stars[control.stars.length] = star[0];
control.inputs[control.inputs.length] = input[0];
control.rater = raters[eid] = rater;
control.context = context;
input.data('rating', control);
rater.data('rating', control);
star.data('rating', control);
context.data('rating', raters);
}); // each element
// Initialize ratings (first draw)
$('.rating-to-be-drawn').rating('draw').removeClass('rating-to-be-drawn');
return this; // don't break the chain...
};
/*--------------------------------------------------------*/
/*
### Core functionality and API ###
*/
$.extend($.fn.rating, {
// Used to append a unique serial number to internal control ID
// each time the plugin is invoked so same name controls can co-exist
calls: 0,
focus: function(){
var control = this.data('rating'); if(!control) return this;
if(!control.focus) return this; // quick fail if not required
// find data for event
var input = $(this).data('rating.input') || $( this.tagName=='INPUT' ? this : null );
// focus handler, as requested by focusdigital.co.uk
if(control.focus) control.focus.apply(input[0], [input.val(), $('a', input.data('rating.star'))[0]]);
}, // $.fn.rating.focus
blur: function(){
var control = this.data('rating'); if(!control) return this;
if(!control.blur) return this; // quick fail if not required
// find data for event
var input = $(this).data('rating.input') || $( this.tagName=='INPUT' ? this : null );
// blur handler, as requested by focusdigital.co.uk
if(control.blur) control.blur.apply(input[0], [input.val(), $('a', input.data('rating.star'))[0]]);
}, // $.fn.rating.blur
fill: function(){ // fill to the current mouse position.
var control = this.data('rating'); if(!control) return this;
// do not execute when control is in read-only mode
if(control.readOnly) return;
// Reset all stars and highlight them up to this element
this.rating('drain');
this.prevAll().andSelf().filter('.rater-'+ control.serial).addClass('star-rating-hover');
},// $.fn.rating.fill
drain: function() { // drain all the stars.
var control = this.data('rating'); if(!control) return this;
// do not execute when control is in read-only mode
if(control.readOnly) return;
// Reset all stars
control.rater.children().filter('.rater-'+ control.serial).removeClass('star-rating-on').removeClass('star-rating-hover');
},// $.fn.rating.drain
draw: function(){ // set value and stars to reflect current selection
var control = this.data('rating'); if(!control) return this;
// Clear all stars
this.rating('drain');
// Set control value
if(control.current){
control.current.data('rating.input').attr('checked','checked');
control.current.prevAll().andSelf().filter('.rater-'+ control.serial).addClass('star-rating-on');
}
else
$(control.inputs).removeAttr('checked');
// Show/hide 'cancel' button
control.cancel[control.readOnly || control.required?'hide':'show']();
// Add/remove read-only classes to remove hand pointer
this.siblings()[control.readOnly?'addClass':'removeClass']('star-rating-readonly');
},// $.fn.rating.draw
select: function(value,wantCallBack){ // select a value
// ***** MODIFICATION *****
// Thanks to faivre.thomas - http://code.google.com/p/jquery-star-rating-plugin/issues/detail?id=27
//
// ***** LIST OF MODIFICATION *****
// ***** added Parameter wantCallBack : false if you don't want a callback. true or undefined if you want postback to be performed at the end of this method'
// ***** recursive calls to this method were like : ... .rating('select') it's now like .rating('select',undefined,wantCallBack); (parameters are set.)
// ***** line which is calling callback
// ***** /LIST OF MODIFICATION *****
var control = this.data('rating'); if(!control) return this;
// do not execute when control is in read-only mode
if(control.readOnly) return;
// clear selection
control.current = null;
// programmatically (based on user input)
if(typeof value!='undefined'){
// select by index (0 based)
if(typeof value=='number')
return $(control.stars[value]).rating('select',undefined,wantCallBack);
// select by literal value (must be passed as a string
if(typeof value=='string')
//return
$.each(control.stars, function(){
if($(this).data('rating.input').val()==value) $(this).rating('select',undefined,wantCallBack);
});
}
else
control.current = this[0].tagName=='INPUT' ?
this.data('rating.star') :
(this.is('.rater-'+ control.serial) ? this : null);
// Update rating control state
this.data('rating', control);
// Update display
this.rating('draw');
// find data for event
var input = $( control.current ? control.current.data('rating.input') : null );
// click callback, as requested here: http://plugins.jquery.com/node/1655
// **** MODIFICATION *****
// Thanks to faivre.thomas - http://code.google.com/p/jquery-star-rating-plugin/issues/detail?id=27
//
//old line doing the callback :
//if(control.callback) control.callback.apply(input[0], [input.val(), $('a', control.current)[0]]);// callback event
//
//new line doing the callback (if i want :)
if((wantCallBack ||wantCallBack == undefined) && control.callback) control.callback.apply(input[0], [input.val(), $('a', control.current)[0]]);// callback event
//to ensure retro-compatibility, wantCallBack must be considered as true by default
// **** /MODIFICATION *****
},// $.fn.rating.select
readOnly: function(toggle, disable){ // make the control read-only (still submits value)
var control = this.data('rating'); if(!control) return this;
// setread-only status
control.readOnly = toggle || toggle==undefined ? true : false;
// enable/disable control value submission
if(disable) $(control.inputs).attr("disabled", "disabled");
else $(control.inputs).removeAttr("disabled");
// Update rating control state
this.data('rating', control);
// Update display
this.rating('draw');
},// $.fn.rating.readOnly
disable: function(){ // make read-only and never submit value
this.rating('readOnly', true, true);
},// $.fn.rating.disable
enable: function(){ // make read/write and submit value
this.rating('readOnly', false, false);
}// $.fn.rating.select
});
/*--------------------------------------------------------*/
/*
### Default Settings ###
eg.: You can override default control like this:
$.fn.rating.options.cancel = 'Clear';
*/
$.fn.rating.options = { //$.extend($.fn.rating, { options: {
cancel: 'Cancel Rating', // advisory title for the 'cancel' link
cancelValue: '', // value to submit when user click the 'cancel' link
split: 0, // split the star into how many parts?
// Width of star image in case the plugin can't work it out. This can happen if
// the jQuery.dimensions plugin is not available OR the image is hidden at installation
starWidth: 16//,
//NB.: These don't need to be pre-defined (can be undefined/null) so let's save some code!
//half: false, // just a shortcut to control.split = 2
//required: false, // disables the 'cancel' button so user can only select one of the specified values
//readOnly: false, // disable rating plugin interaction/ values cannot be changed
//focus: function(){}, // executed when stars are focused
//blur: function(){}, // executed when stars are focused
//callback: function(){}, // executed when a star is clicked
}; //} });
/*--------------------------------------------------------*/
/*
### Default implementation ###
The plugin will attach itself to file inputs
with the class 'multi' when the page loads
*/
$(function(){
$('input[type=radio].star').rating();
});
/*# AVOID COLLISIONS #*/
})(jQuery);
/*# AVOID COLLISIONS #*/
| 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.
*/
/*
* 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.
*/
(function($) {
var ajax = $.ajax;
var pendingRequests = {};
var synced = [];
var syncedData = [];
$.ajax = function(settings) {
// create settings for compatibility with ajaxSetup
settings = jQuery.extend(settings, jQuery.extend({}, jQuery.ajaxSettings, settings));
var port = settings.port;
switch(settings.mode) {
case "abort":
if ( pendingRequests[port] ) {
pendingRequests[port].abort();
}
return pendingRequests[port] = ajax.apply(this, arguments);
case "queue":
var _old = settings.complete;
settings.complete = function(){
if ( _old )
_old.apply( this, arguments );
jQuery([ajax]).dequeue("ajax" + port );;
};
jQuery([ ajax ]).queue("ajax" + port, function(){
ajax( settings );
});
return;
case "sync":
var pos = synced.length;
synced[ pos ] = {
error: settings.error,
success: settings.success,
complete: settings.complete,
done: false
};
syncedData[ pos ] = {
error: [],
success: [],
complete: []
};
settings.error = function(){ syncedData[ pos ].error = arguments; };
settings.success = function(){ syncedData[ pos ].success = arguments; };
settings.complete = function(){
syncedData[ pos ].complete = arguments;
synced[ pos ].done = true;
if ( pos == 0 || !synced[ pos-1 ] )
for ( var i = pos; i < synced.length && synced[i].done; i++ ) {
if ( synced[i].error ) synced[i].error.apply( jQuery, syncedData[i].error );
if ( synced[i].success ) synced[i].success.apply( jQuery, syncedData[i].success );
if ( synced[i].complete ) synced[i].complete.apply( jQuery, syncedData[i].complete );
synced[i] = null;
syncedData[i] = null;
}
};
}
return ajax.apply(this, arguments);
};
})(jQuery); | JavaScript |
/*
* jQuery Autocomplete plugin 1.1
*
* Modified for Yii Framework:
* - Renamed "autocomplete" to "legacyautocomplete".
* - Fixed IE8 problems (mario.ffranco).
*
* Copyright (c) 2009 Jörn Zaefferer
*
* Dual licensed under the MIT and GPL licenses:
* http://www.opensource.org/licenses/mit-license.php
* http://www.gnu.org/licenses/gpl.html
*
* Revision: $Id: jquery.autocomplete.js 15 2009-08-22 10:30:27Z joern.zaefferer $
*/
;(function($) {
$.fn.extend({
legacyautocomplete: function(urlOrData, options) {
var isUrl = typeof urlOrData == "string";
options = $.extend({}, $.Autocompleter.defaults, {
url: isUrl ? urlOrData : null,
data: isUrl ? null : urlOrData,
delay: isUrl ? $.Autocompleter.defaults.delay : 10,
max: options && !options.scroll ? 10 : 150
}, options);
// if highlight is set to false, replace it with a do-nothing function
options.highlight = options.highlight || function(value) { return value; };
// if the formatMatch option is not specified, then use formatItem for backwards compatibility
options.formatMatch = options.formatMatch || options.formatItem;
return this.each(function() {
new $.Autocompleter(this, options);
});
},
result: function(handler) {
return this.bind("result", handler);
},
search: function(handler) {
return this.trigger("search", [handler]);
},
flushCache: function() {
return this.trigger("flushCache");
},
setOptions: function(options){
return this.trigger("setOptions", [options]);
},
unautocomplete: function() {
return this.trigger("unautocomplete");
}
});
$.Autocompleter = function(input, options) {
var KEY = {
UP: 38,
DOWN: 40,
DEL: 46,
TAB: 9,
RETURN: 13,
ESC: 27,
COMMA: 188,
PAGEUP: 33,
PAGEDOWN: 34,
BACKSPACE: 8
};
// Create $ object for input element
var $input = $(input).attr("autocomplete", "off").addClass(options.inputClass);
var timeout;
var previousValue = "";
var cache = $.Autocompleter.Cache(options);
var hasFocus = 0;
var lastKeyPressCode;
var config = {
mouseDownOnSelect: false
};
var select = $.Autocompleter.Select(options, input, selectCurrent, config);
var blockSubmit;
// prevent form submit in opera when selecting with return key
$.browser.opera && $(input.form).bind("submit.autocomplete", function() {
if (blockSubmit) {
blockSubmit = false;
return false;
}
});
// only opera doesn't trigger keydown multiple times while pressed, others don't work with keypress at all
$input.bind(($.browser.opera ? "keypress" : "keydown") + ".autocomplete", function(event) {
// a keypress means the input has focus
// avoids issue where input had focus before the autocomplete was applied
hasFocus = 1;
// track last key pressed
lastKeyPressCode = event.keyCode;
switch(event.keyCode) {
case KEY.UP:
event.preventDefault();
if ( select.visible() ) {
select.prev();
} else {
onChange(0, true);
}
break;
case KEY.DOWN:
event.preventDefault();
if ( select.visible() ) {
select.next();
} else {
onChange(0, true);
}
break;
case KEY.PAGEUP:
event.preventDefault();
if ( select.visible() ) {
select.pageUp();
} else {
onChange(0, true);
}
break;
case KEY.PAGEDOWN:
event.preventDefault();
if ( select.visible() ) {
select.pageDown();
} else {
onChange(0, true);
}
break;
// matches also semicolon
case options.multiple && $.trim(options.multipleSeparator) == "," && KEY.COMMA:
case KEY.TAB:
case KEY.RETURN:
if( selectCurrent() ) {
// stop default to prevent a form submit, Opera needs special handling
event.preventDefault();
blockSubmit = true;
return false;
}
break;
case KEY.ESC:
select.hide();
break;
default:
clearTimeout(timeout);
timeout = setTimeout(onChange, options.delay);
break;
}
}).focus(function(){
// track whether the field has focus, we shouldn't process any
// results if the field no longer has focus
hasFocus++;
}).blur(function() {
hasFocus = 0;
if (!config.mouseDownOnSelect) {
hideResults();
}
}).click(function() {
// show select when clicking in a focused field
if ( hasFocus++ > 1 && !select.visible() ) {
onChange(0, true);
}
}).bind("search", function() {
// TODO why not just specifying both arguments?
var fn = (arguments.length > 1) ? arguments[1] : null;
function findValueCallback(q, data) {
var result;
if( data && data.length ) {
for (var i=0; i < data.length; i++) {
if( data[i].result.toLowerCase() == q.toLowerCase() ) {
result = data[i];
break;
}
}
}
if( typeof fn == "function" ) fn(result);
else $input.trigger("result", result && [result.data, result.value]);
}
$.each(trimWords($input.val()), function(i, value) {
request(value, findValueCallback, findValueCallback);
});
}).bind("flushCache", function() {
cache.flush();
}).bind("setOptions", function() {
$.extend(options, arguments[1]);
// if we've updated the data, repopulate
if ( "data" in arguments[1] )
cache.populate();
}).bind("unautocomplete", function() {
select.unbind();
$input.unbind();
$(input.form).unbind(".autocomplete");
});
function selectCurrent() {
var selected = select.selected();
if( !selected )
return false;
var v = selected.result;
previousValue = v;
if ( options.multiple ) {
var words = trimWords($input.val());
if ( words.length > 1 ) {
var seperator = options.multipleSeparator.length;
var cursorAt = $(input).selection().start;
var wordAt, progress = 0;
$.each(words, function(i, word) {
progress += word.length;
if (cursorAt <= progress) {
wordAt = i;
// Following return caused IE8 to set cursor to the start of the line.
// return false;
}
progress += seperator;
});
words[wordAt] = v;
// TODO this should set the cursor to the right position, but it gets overriden somewhere
//$.Autocompleter.Selection(input, progress + seperator, progress + seperator);
v = words.join( options.multipleSeparator );
}
v += options.multipleSeparator;
}
$input.val(v);
hideResultsNow();
$input.trigger("result", [selected.data, selected.value]);
return true;
}
function onChange(crap, skipPrevCheck) {
if( lastKeyPressCode == KEY.DEL ) {
select.hide();
return;
}
var currentValue = $input.val();
if ( !skipPrevCheck && currentValue == previousValue )
return;
previousValue = currentValue;
currentValue = lastWord(currentValue);
if ( currentValue.length >= options.minChars) {
$input.addClass(options.loadingClass);
if (!options.matchCase)
currentValue = currentValue.toLowerCase();
request(currentValue, receiveData, hideResultsNow);
} else {
stopLoading();
select.hide();
}
};
function trimWords(value) {
if (!value)
return [""];
if (!options.multiple)
return [$.trim(value)];
return $.map(value.split(options.multipleSeparator), function(word) {
return $.trim(value).length ? $.trim(word) : null;
});
}
function lastWord(value) {
if ( !options.multiple )
return value;
var words = trimWords(value);
if (words.length == 1)
return words[0];
var cursorAt = $(input).selection().start;
if (cursorAt == value.length) {
words = trimWords(value)
} else {
words = trimWords(value.replace(value.substring(cursorAt), ""));
}
return words[words.length - 1];
}
// fills in the input box w/the first match (assumed to be the best match)
// q: the term entered
// sValue: the first matching result
function autoFill(q, sValue){
// autofill in the complete box w/the first match as long as the user hasn't entered in more data
// if the last user key pressed was backspace, don't autofill
if( options.autoFill && (lastWord($input.val()).toLowerCase() == q.toLowerCase()) && lastKeyPressCode != KEY.BACKSPACE ) {
// fill in the value (keep the case the user has typed)
$input.val($input.val() + sValue.substring(lastWord(previousValue).length));
// select the portion of the value not typed by the user (so the next character will erase)
$(input).selection(previousValue.length, previousValue.length + sValue.length);
}
};
function hideResults() {
clearTimeout(timeout);
timeout = setTimeout(hideResultsNow, 200);
};
function hideResultsNow() {
var wasVisible = select.visible();
select.hide();
clearTimeout(timeout);
stopLoading();
if (options.mustMatch) {
// call search and run callback
$input.search(
function (result){
// if no value found, clear the input box
if( !result ) {
if (options.multiple) {
var words = trimWords($input.val()).slice(0, -1);
$input.val( words.join(options.multipleSeparator) + (words.length ? options.multipleSeparator : "") );
}
else {
$input.val( "" );
$input.trigger("result", null);
}
}
}
);
}
};
function receiveData(q, data) {
if ( data && data.length && hasFocus ) {
stopLoading();
select.display(data, q);
autoFill(q, data[0].value);
select.show();
} else {
hideResultsNow();
}
};
function request(term, success, failure) {
if (!options.matchCase)
term = term.toLowerCase();
var data = cache.load(term);
// recieve the cached data
if (data && data.length) {
success(term, data);
// if an AJAX url has been supplied, try loading the data now
} else if( (typeof options.url == "string") && (options.url.length > 0) ){
var extraParams = {
timestamp: +new Date()
};
$.each(options.extraParams, function(key, param) {
extraParams[key] = typeof param == "function" ? param() : param;
});
$.ajax({
// try to leverage ajaxQueue plugin to abort previous requests
mode: "abort",
// limit abortion to this input
port: "autocomplete" + input.name,
dataType: options.dataType,
url: options.url,
data: $.extend({
q: lastWord(term),
limit: options.max
}, extraParams),
success: function(data) {
var parsed = options.parse && options.parse(data) || parse(data);
cache.add(term, parsed);
success(term, parsed);
}
});
} else {
// if we have a failure, we need to empty the list -- this prevents the the [TAB] key from selecting the last successful match
select.emptyList();
failure(term);
}
};
function parse(data) {
var parsed = [];
var rows = data.split("\n");
for (var i=0; i < rows.length; i++) {
var row = $.trim(rows[i]);
if (row) {
row = row.split("|");
parsed[parsed.length] = {
data: row,
value: row[0],
result: options.formatResult && options.formatResult(row, row[0]) || row[0]
};
}
}
return parsed;
};
function stopLoading() {
$input.removeClass(options.loadingClass);
};
};
$.Autocompleter.defaults = {
inputClass: "ac_input",
resultsClass: "ac_results",
loadingClass: "ac_loading",
minChars: 1,
delay: 400,
matchCase: false,
matchSubset: true,
matchContains: false,
cacheLength: 10,
max: 100,
mustMatch: false,
extraParams: {},
selectFirst: true,
formatItem: function(row) { return row[0]; },
formatMatch: null,
autoFill: false,
width: 0,
multiple: false,
multipleSeparator: ", ",
highlight: function(value, term) {
return value.replace(new RegExp("(?![^&;]+;)(?!<[^<>]*)(" + term.replace(/([\^\$\(\)\[\]\{\}\*\.\+\?\|\\])/gi, "\\$1") + ")(?![^<>]*>)(?![^&;]+;)", "gi"), "<strong>$1</strong>");
},
scroll: true,
scrollHeight: 180
};
$.Autocompleter.Cache = function(options) {
var data = {};
var length = 0;
function matchSubset(s, sub) {
if (!options.matchCase)
s = s.toLowerCase();
var i = s.indexOf(sub);
if (options.matchContains == "word"){
i = s.toLowerCase().search("\\b" + sub.toLowerCase());
}
if (i == -1) return false;
return i == 0 || options.matchContains;
};
function add(q, value) {
if (length > options.cacheLength){
flush();
}
if (!data[q]){
length++;
}
data[q] = value;
}
function populate(){
if( !options.data ) return false;
// track the matches
var stMatchSets = {},
nullData = 0;
// no url was specified, we need to adjust the cache length to make sure it fits the local data store
if( !options.url ) options.cacheLength = 1;
// track all options for minChars = 0
stMatchSets[""] = [];
// loop through the array and create a lookup structure
for ( var i = 0, ol = options.data.length; i < ol; i++ ) {
var rawValue = options.data[i];
// if rawValue is a string, make an array otherwise just reference the array
rawValue = (typeof rawValue == "string") ? [rawValue] : rawValue;
var value = options.formatMatch(rawValue, i+1, options.data.length);
if ( value === false )
continue;
var firstChar = value.charAt(0).toLowerCase();
// if no lookup array for this character exists, look it up now
if( !stMatchSets[firstChar] )
stMatchSets[firstChar] = [];
// if the match is a string
var row = {
value: value,
data: rawValue,
result: options.formatResult && options.formatResult(rawValue) || value
};
// push the current match into the set list
stMatchSets[firstChar].push(row);
// keep track of minChars zero items
if ( nullData++ < options.max ) {
stMatchSets[""].push(row);
}
};
// add the data items to the cache
$.each(stMatchSets, function(i, value) {
// increase the cache size
options.cacheLength++;
// add to the cache
add(i, value);
});
}
// populate any existing data
setTimeout(populate, 25);
function flush(){
data = {};
length = 0;
}
return {
flush: flush,
add: add,
populate: populate,
load: function(q) {
if (!options.cacheLength || !length)
return null;
/*
* if dealing w/local data and matchContains than we must make sure
* to loop through all the data collections looking for matches
*/
if( !options.url && options.matchContains ){
// track all matches
var csub = [];
// loop through all the data grids for matches
for( var k in data ){
// don't search through the stMatchSets[""] (minChars: 0) cache
// this prevents duplicates
if( k.length > 0 ){
var c = data[k];
$.each(c, function(i, x) {
// if we've got a match, add it to the array
if (matchSubset(x.value, q)) {
csub.push(x);
}
});
}
}
return csub;
} else
// if the exact item exists, use it
if (data[q]){
return data[q];
} else
if (options.matchSubset) {
for (var i = q.length - 1; i >= options.minChars; i--) {
var c = data[q.substr(0, i)];
if (c) {
var csub = [];
$.each(c, function(i, x) {
if (matchSubset(x.value, q)) {
csub[csub.length] = x;
}
});
return csub;
}
}
}
return null;
}
};
};
$.Autocompleter.Select = function (options, input, select, config) {
var CLASSES = {
ACTIVE: "ac_over"
};
var listItems,
active = -1,
data,
term = "",
needsInit = true,
element,
list;
// Create results
function init() {
if (!needsInit)
return;
element = $("<div/>")
.hide()
.addClass(options.resultsClass)
.css("position", "absolute")
.appendTo(document.body);
list = $("<ul/>").appendTo(element).mouseover( function(event) {
if(target(event).nodeName && target(event).nodeName.toUpperCase() == 'LI') {
active = $("li", list).removeClass(CLASSES.ACTIVE).index(target(event));
$(target(event)).addClass(CLASSES.ACTIVE);
}
}).click(function(event) {
$(target(event)).addClass(CLASSES.ACTIVE);
select();
// TODO provide option to avoid setting focus again after selection? useful for cleanup-on-focus
input.focus();
return false;
}).mousedown(function() {
config.mouseDownOnSelect = true;
}).mouseup(function() {
config.mouseDownOnSelect = false;
});
if( options.width > 0 )
element.css("width", options.width);
needsInit = false;
}
function target(event) {
var element = event.target;
while(element && element.tagName != "LI")
element = element.parentNode;
// more fun with IE, sometimes event.target is empty, just ignore it then
if(!element)
return [];
return element;
}
function moveSelect(step) {
listItems.slice(active, active + 1).removeClass(CLASSES.ACTIVE);
movePosition(step);
var activeItem = listItems.slice(active, active + 1).addClass(CLASSES.ACTIVE);
if(options.scroll) {
var offset = 0;
listItems.slice(0, active).each(function() {
offset += this.offsetHeight;
});
if((offset + activeItem[0].offsetHeight - list.scrollTop()) > list[0].clientHeight) {
list.scrollTop(offset + activeItem[0].offsetHeight - list.innerHeight());
} else if(offset < list.scrollTop()) {
list.scrollTop(offset);
}
}
};
function movePosition(step) {
active += step;
if (active < 0) {
active = listItems.size() - 1;
} else if (active >= listItems.size()) {
active = 0;
}
}
function limitNumberOfItems(available) {
return options.max && options.max < available
? options.max
: available;
}
function fillList() {
list.empty();
var max = limitNumberOfItems(data.length);
for (var i=0; i < max; i++) {
if (!data[i])
continue;
var formatted = options.formatItem(data[i].data, i+1, max, data[i].value, term);
if ( formatted === false )
continue;
var li = $("<li/>").html( options.highlight(formatted, term) ).addClass(i%2 == 0 ? "ac_even" : "ac_odd").appendTo(list)[0];
$.data(li, "ac_data", data[i]);
}
listItems = list.find("li");
if ( options.selectFirst ) {
listItems.slice(0, 1).addClass(CLASSES.ACTIVE);
active = 0;
}
// apply bgiframe if available
if ( $.fn.bgiframe )
list.bgiframe();
}
return {
display: function(d, q) {
init();
data = d;
term = q;
fillList();
},
next: function() {
moveSelect(1);
},
prev: function() {
moveSelect(-1);
},
pageUp: function() {
if (active != 0 && active - 8 < 0) {
moveSelect( -active );
} else {
moveSelect(-8);
}
},
pageDown: function() {
if (active != listItems.size() - 1 && active + 8 > listItems.size()) {
moveSelect( listItems.size() - 1 - active );
} else {
moveSelect(8);
}
},
hide: function() {
element && element.hide();
listItems && listItems.removeClass(CLASSES.ACTIVE);
active = -1;
},
visible : function() {
return element && element.is(":visible");
},
current: function() {
return this.visible() && (listItems.filter("." + CLASSES.ACTIVE)[0] || options.selectFirst && listItems[0]);
},
show: function() {
var offset = $(input).offset();
element.css({
width: typeof options.width == "string" || options.width > 0 ? options.width : $(input).width(),
top: offset.top + input.offsetHeight,
left: offset.left
}).show();
if(options.scroll) {
list.scrollTop(0);
list.css({
maxHeight: options.scrollHeight,
overflow: 'auto'
});
if($.browser.msie && typeof document.body.style.maxHeight === "undefined") {
var listHeight = 0;
listItems.each(function() {
listHeight += this.offsetHeight;
});
var scrollbarsVisible = listHeight > options.scrollHeight;
list.css('height', scrollbarsVisible ? options.scrollHeight : listHeight );
if (!scrollbarsVisible) {
// IE doesn't recalculate width when scrollbar disappears
listItems.width( list.width() - parseInt(listItems.css("padding-left")) - parseInt(listItems.css("padding-right")) );
}
}
}
},
selected: function() {
var selected = listItems && listItems.filter("." + CLASSES.ACTIVE).removeClass(CLASSES.ACTIVE);
return selected && selected.length && $.data(selected[0], "ac_data");
},
emptyList: function (){
list && list.empty();
},
unbind: function() {
element && element.remove();
}
};
};
$.fn.selection = function(start, end) {
if (start !== undefined) {
return this.each(function() {
if( this.createTextRange ){
var selRange = this.createTextRange();
if (end === undefined || start == end) {
selRange.move("character", start);
selRange.select();
} else {
selRange.collapse(true);
selRange.moveStart("character", start);
selRange.moveEnd("character", end);
selRange.select();
}
} else if( this.setSelectionRange ){
this.setSelectionRange(start, end);
} else if( this.selectionStart ){
this.selectionStart = start;
this.selectionEnd = end;
}
});
}
var field = this[0];
if ( field.createTextRange ) {
var range = document.selection.createRange(),
orig = field.value,
teststring = "<->",
textLength = range.text.length;
range.text = teststring;
var caretAt = field.value.indexOf(teststring);
field.value = orig;
this.selection(caretAt, caretAt + textLength);
return {
start: caretAt,
end: caretAt + textLength
}
} else if( field.selectionStart !== undefined ){
return {
start: field.selectionStart,
end: field.selectionEnd
}
}
};
})(jQuery); | JavaScript |
/*!
* jQuery BBQ: Back Button & Query Library - v1.2.1 - 2/17/2010
* http://benalman.com/projects/jquery-bbq-plugin/
*
* Copyright (c) 2010 "Cowboy" Ben Alman
* Dual licensed under the MIT and GPL licenses.
* http://benalman.com/about/license/
*/
// Script: jQuery BBQ: Back Button & Query Library
//
// *Version: 1.2.1, Last updated: 2/17/2010*
//
// Project Home - http://benalman.com/projects/jquery-bbq-plugin/
// GitHub - http://github.com/cowboy/jquery-bbq/
// Source - http://github.com/cowboy/jquery-bbq/raw/master/jquery.ba-bbq.js
// (Minified) - http://github.com/cowboy/jquery-bbq/raw/master/jquery.ba-bbq.min.js (4.0kb)
//
// About: License
//
// Copyright (c) 2010 "Cowboy" Ben Alman,
// Dual licensed under the MIT and GPL licenses.
// http://benalman.com/about/license/
//
// About: Examples
//
// These working examples, complete with fully commented code, illustrate a few
// ways in which this plugin can be used.
//
// Basic AJAX - http://benalman.com/code/projects/jquery-bbq/examples/fragment-basic/
// Advanced AJAX - http://benalman.com/code/projects/jquery-bbq/examples/fragment-advanced/
// jQuery UI Tabs - http://benalman.com/code/projects/jquery-bbq/examples/fragment-jquery-ui-tabs/
// Deparam - http://benalman.com/code/projects/jquery-bbq/examples/deparam/
//
// About: Support and Testing
//
// Information about what version or versions of jQuery this plugin has been
// tested with, what browsers it has been tested in, and where the unit tests
// reside (so you can test it yourself).
//
// jQuery Versions - 1.3.2, 1.4.1, 1.4.2
// Browsers Tested - Internet Explorer 6-8, Firefox 2-3.7, Safari 3-4,
// Chrome 4-5, Opera 9.6-10.1.
// Unit Tests - http://benalman.com/code/projects/jquery-bbq/unit/
//
// About: Release History
//
// 1.2.1 - (2/17/2010) Actually fixed the stale window.location Safari bug from
// <jQuery hashchange event> in BBQ, which was the main reason for the
// previous release!
// 1.2 - (2/16/2010) Integrated <jQuery hashchange event> v1.2, which fixes a
// Safari bug, the event can now be bound before DOM ready, and IE6/7
// page should no longer scroll when the event is first bound. Also
// added the <jQuery.param.fragment.noEscape> method, and reworked the
// <hashchange event (BBQ)> internal "add" method to be compatible with
// changes made to the jQuery 1.4.2 special events API.
// 1.1.1 - (1/22/2010) Integrated <jQuery hashchange event> v1.1, which fixes an
// obscure IE8 EmulateIE7 meta tag compatibility mode bug.
// 1.1 - (1/9/2010) Broke out the jQuery BBQ event.special <hashchange event>
// functionality into a separate plugin for users who want just the
// basic event & back button support, without all the extra awesomeness
// that BBQ provides. This plugin will be included as part of jQuery BBQ,
// but also be available separately. See <jQuery hashchange event>
// plugin for more information. Also added the <jQuery.bbq.removeState>
// method and added additional <jQuery.deparam> examples.
// 1.0.3 - (12/2/2009) Fixed an issue in IE 6 where location.search and
// location.hash would report incorrectly if the hash contained the ?
// character. Also <jQuery.param.querystring> and <jQuery.param.fragment>
// will no longer parse params out of a URL that doesn't contain ? or #,
// respectively.
// 1.0.2 - (10/10/2009) Fixed an issue in IE 6/7 where the hidden IFRAME caused
// a "This page contains both secure and nonsecure items." warning when
// used on an https:// page.
// 1.0.1 - (10/7/2009) Fixed an issue in IE 8. Since both "IE7" and "IE8
// Compatibility View" modes erroneously report that the browser
// supports the native window.onhashchange event, a slightly more
// robust test needed to be added.
// 1.0 - (10/2/2009) Initial release
(function($,window){
'$:nomunge'; // Used by YUI compressor.
// Some convenient shortcuts.
var undefined,
aps = Array.prototype.slice,
decode = decodeURIComponent,
// Method / object references.
jq_param = $.param,
jq_param_fragment,
jq_deparam,
jq_deparam_fragment,
jq_bbq = $.bbq = $.bbq || {},
jq_bbq_pushState,
jq_bbq_getState,
jq_elemUrlAttr,
jq_event_special = $.event.special,
// Reused strings.
str_hashchange = 'hashchange',
str_querystring = 'querystring',
str_fragment = 'fragment',
str_elemUrlAttr = 'elemUrlAttr',
str_location = 'location',
str_href = 'href',
str_src = 'src',
// Reused RegExp.
re_trim_querystring = /^.*\?|#.*$/g,
re_trim_fragment = /^.*\#/,
re_no_escape,
// Used by jQuery.elemUrlAttr.
elemUrlAttr_cache = {};
// A few commonly used bits, broken out to help reduce minified file size.
function is_string( arg ) {
return typeof arg === 'string';
};
// Why write the same function twice? Let's curry! Mmmm, curry..
function curry( func ) {
var args = aps.call( arguments, 1 );
return function() {
return func.apply( this, args.concat( aps.call( arguments ) ) );
};
};
// Get location.hash (or what you'd expect location.hash to be) sans any
// leading #. Thanks for making this necessary, Firefox!
function get_fragment( url ) {
return url.replace( /^[^#]*#?(.*)$/, '$1' );
};
// Get location.search (or what you'd expect location.search to be) sans any
// leading #. Thanks for making this necessary, IE6!
function get_querystring( url ) {
return url.replace( /(?:^[^?#]*\?([^#]*).*$)?.*/, '$1' );
};
// Section: Param (to string)
//
// Method: jQuery.param.querystring
//
// Retrieve the query string from a URL or if no arguments are passed, the
// current window.location.
//
// Usage:
//
// > jQuery.param.querystring( [ url ] );
//
// Arguments:
//
// url - (String) A URL containing query string params to be parsed. If url
// is not passed, the current window.location is used.
//
// Returns:
//
// (String) The parsed query string, with any leading "?" removed.
//
// Method: jQuery.param.querystring (build url)
//
// Merge a URL, with or without pre-existing query string params, plus any
// object, params string or URL containing query string params into a new URL.
//
// Usage:
//
// > jQuery.param.querystring( url, params [, merge_mode ] );
//
// Arguments:
//
// url - (String) A valid URL for params to be merged into. This URL may
// contain a query string and/or fragment (hash).
// params - (String) A params string or URL containing query string params to
// be merged into url.
// params - (Object) A params object to be merged into url.
// merge_mode - (Number) Merge behavior defaults to 0 if merge_mode is not
// specified, and is as-follows:
//
// * 0: params in the params argument will override any query string
// params in url.
// * 1: any query string params in url will override params in the params
// argument.
// * 2: params argument will completely replace any query string in url.
//
// Returns:
//
// (String) Either a params string with urlencoded data or a URL with a
// urlencoded query string in the format 'a=b&c=d&e=f'.
// Method: jQuery.param.fragment
//
// Retrieve the fragment (hash) from a URL or if no arguments are passed, the
// current window.location.
//
// Usage:
//
// > jQuery.param.fragment( [ url ] );
//
// Arguments:
//
// url - (String) A URL containing fragment (hash) params to be parsed. If
// url is not passed, the current window.location is used.
//
// Returns:
//
// (String) The parsed fragment (hash) string, with any leading "#" removed.
// Method: jQuery.param.fragment (build url)
//
// Merge a URL, with or without pre-existing fragment (hash) params, plus any
// object, params string or URL containing fragment (hash) params into a new
// URL.
//
// Usage:
//
// > jQuery.param.fragment( url, params [, merge_mode ] );
//
// Arguments:
//
// url - (String) A valid URL for params to be merged into. This URL may
// contain a query string and/or fragment (hash).
// params - (String) A params string or URL containing fragment (hash) params
// to be merged into url.
// params - (Object) A params object to be merged into url.
// merge_mode - (Number) Merge behavior defaults to 0 if merge_mode is not
// specified, and is as-follows:
//
// * 0: params in the params argument will override any fragment (hash)
// params in url.
// * 1: any fragment (hash) params in url will override params in the
// params argument.
// * 2: params argument will completely replace any query string in url.
//
// Returns:
//
// (String) Either a params string with urlencoded data or a URL with a
// urlencoded fragment (hash) in the format 'a=b&c=d&e=f'.
function jq_param_sub( is_fragment, get_func, url, params, merge_mode ) {
var result,
qs,
matches,
url_params,
hash;
if ( params !== undefined ) {
// Build URL by merging params into url string.
// matches[1] = url part that precedes params, not including trailing ?/#
// matches[2] = params, not including leading ?/#
// matches[3] = if in 'querystring' mode, hash including leading #, otherwise ''
matches = url.match( is_fragment ? /^([^#]*)\#?(.*)$/ : /^([^#?]*)\??([^#]*)(#?.*)/ );
// Get the hash if in 'querystring' mode, and it exists.
hash = matches[3] || '';
if ( merge_mode === 2 && is_string( params ) ) {
// If merge_mode is 2 and params is a string, merge the fragment / query
// string into the URL wholesale, without converting it into an object.
qs = params.replace( is_fragment ? re_trim_fragment : re_trim_querystring, '' );
} else {
// Convert relevant params in url to object.
url_params = jq_deparam( matches[2] );
params = is_string( params )
// Convert passed params string into object.
? jq_deparam[ is_fragment ? str_fragment : str_querystring ]( params )
// Passed params object.
: params;
qs = merge_mode === 2 ? params // passed params replace url params
: merge_mode === 1 ? $.extend( {}, params, url_params ) // url params override passed params
: $.extend( {}, url_params, params ); // passed params override url params
// Convert params object to a string.
qs = jq_param( qs );
// Unescape characters specified via $.param.noEscape. Since only hash-
// history users have requested this feature, it's only enabled for
// fragment-related params strings.
if ( is_fragment ) {
qs = qs.replace( re_no_escape, decode );
}
}
// Build URL from the base url, querystring and hash. In 'querystring'
// mode, ? is only added if a query string exists. In 'fragment' mode, #
// is always added.
result = matches[1] + ( is_fragment ? '#' : qs || !matches[1] ? '?' : '' ) + qs + hash;
} else {
// If URL was passed in, parse params from URL string, otherwise parse
// params from window.location.
result = get_func( url !== undefined ? url : window[ str_location ][ str_href ] );
}
return result;
};
jq_param[ str_querystring ] = curry( jq_param_sub, 0, get_querystring );
jq_param[ str_fragment ] = jq_param_fragment = curry( jq_param_sub, 1, get_fragment );
// Method: jQuery.param.fragment.noEscape
//
// Specify characters that will be left unescaped when fragments are created
// or merged using <jQuery.param.fragment>, or when the fragment is modified
// using <jQuery.bbq.pushState>. This option only applies to serialized data
// object fragments, and not set-as-string fragments. Does not affect the
// query string. Defaults to ",/" (comma, forward slash).
//
// Note that this is considered a purely aesthetic option, and will help to
// create URLs that "look pretty" in the address bar or bookmarks, without
// affecting functionality in any way. That being said, be careful to not
// unescape characters that are used as delimiters or serve a special
// purpose, such as the "#?&=+" (octothorpe, question mark, ampersand,
// equals, plus) characters.
//
// Usage:
//
// > jQuery.param.fragment.noEscape( [ chars ] );
//
// Arguments:
//
// chars - (String) The characters to not escape in the fragment. If
// unspecified, defaults to empty string (escape all characters).
//
// Returns:
//
// Nothing.
jq_param_fragment.noEscape = function( chars ) {
chars = chars || '';
var arr = $.map( chars.split(''), encodeURIComponent );
re_no_escape = new RegExp( arr.join('|'), 'g' );
};
// A sensible default. These are the characters people seem to complain about
// "uglifying up the URL" the most.
jq_param_fragment.noEscape( ',/' );
// Section: Deparam (from string)
//
// Method: jQuery.deparam
//
// Deserialize a params string into an object, optionally coercing numbers,
// booleans, null and undefined values; this method is the counterpart to the
// internal jQuery.param method.
//
// Usage:
//
// > jQuery.deparam( params [, coerce ] );
//
// Arguments:
//
// params - (String) A params string to be parsed.
// coerce - (Boolean) If true, coerces any numbers or true, false, null, and
// undefined to their actual value. Defaults to false if omitted.
//
// Returns:
//
// (Object) An object representing the deserialized params string.
$.deparam = jq_deparam = function( params, coerce ) {
var obj = {},
coerce_types = { 'true': !0, 'false': !1, 'null': null };
// Iterate over all name=value pairs.
$.each( params.replace( /\+/g, ' ' ).split( '&' ), function(j,v){
var param = v.split( '=' ),
key = decode( param[0] ),
val,
cur = obj,
i = 0,
// If key is more complex than 'foo', like 'a[]' or 'a[b][c]', split it
// into its component parts.
keys = key.split( '][' ),
keys_last = keys.length - 1;
// If the first keys part contains [ and the last ends with ], then []
// are correctly balanced.
if ( /\[/.test( keys[0] ) && /\]$/.test( keys[ keys_last ] ) ) {
// Remove the trailing ] from the last keys part.
keys[ keys_last ] = keys[ keys_last ].replace( /\]$/, '' );
// Split first keys part into two parts on the [ and add them back onto
// the beginning of the keys array.
keys = keys.shift().split('[').concat( keys );
keys_last = keys.length - 1;
} else {
// Basic 'foo' style key.
keys_last = 0;
}
// Are we dealing with a name=value pair, or just a name?
if ( param.length === 2 ) {
val = decode( param[1] );
// Coerce values.
if ( coerce ) {
val = val && !isNaN(val) ? +val // number
: val === 'undefined' ? undefined // undefined
: coerce_types[val] !== undefined ? coerce_types[val] // true, false, null
: val; // string
}
if ( keys_last ) {
// Complex key, build deep object structure based on a few rules:
// * The 'cur' pointer starts at the object top-level.
// * [] = array push (n is set to array length), [n] = array if n is
// numeric, otherwise object.
// * If at the last keys part, set the value.
// * For each keys part, if the current level is undefined create an
// object or array based on the type of the next keys part.
// * Move the 'cur' pointer to the next level.
// * Rinse & repeat.
for ( ; i <= keys_last; i++ ) {
key = keys[i] === '' ? cur.length : keys[i];
cur = cur[key] = i < keys_last
? cur[key] || ( keys[i+1] && isNaN( keys[i+1] ) ? {} : [] )
: val;
}
} else {
// Simple key, even simpler rules, since only scalars and shallow
// arrays are allowed.
if ( $.isArray( obj[key] ) ) {
// val is already an array, so push on the next value.
obj[key].push( val );
} else if ( obj[key] !== undefined ) {
// val isn't an array, but since a second value has been specified,
// convert val into an array.
obj[key] = [ obj[key], val ];
} else {
// val is a scalar.
obj[key] = val;
}
}
} else if ( key ) {
// No value was defined, so set something meaningful.
obj[key] = coerce
? undefined
: '';
}
});
return obj;
};
// Method: jQuery.deparam.querystring
//
// Parse the query string from a URL or the current window.location,
// deserializing it into an object, optionally coercing numbers, booleans,
// null and undefined values.
//
// Usage:
//
// > jQuery.deparam.querystring( [ url ] [, coerce ] );
//
// Arguments:
//
// url - (String) An optional params string or URL containing query string
// params to be parsed. If url is omitted, the current window.location
// is used.
// coerce - (Boolean) If true, coerces any numbers or true, false, null, and
// undefined to their actual value. Defaults to false if omitted.
//
// Returns:
//
// (Object) An object representing the deserialized params string.
// Method: jQuery.deparam.fragment
//
// Parse the fragment (hash) from a URL or the current window.location,
// deserializing it into an object, optionally coercing numbers, booleans,
// null and undefined values.
//
// Usage:
//
// > jQuery.deparam.fragment( [ url ] [, coerce ] );
//
// Arguments:
//
// url - (String) An optional params string or URL containing fragment (hash)
// params to be parsed. If url is omitted, the current window.location
// is used.
// coerce - (Boolean) If true, coerces any numbers or true, false, null, and
// undefined to their actual value. Defaults to false if omitted.
//
// Returns:
//
// (Object) An object representing the deserialized params string.
function jq_deparam_sub( is_fragment, url_or_params, coerce ) {
if ( url_or_params === undefined || typeof url_or_params === 'boolean' ) {
// url_or_params not specified.
coerce = url_or_params;
url_or_params = jq_param[ is_fragment ? str_fragment : str_querystring ]();
} else {
url_or_params = is_string( url_or_params )
? url_or_params.replace( is_fragment ? re_trim_fragment : re_trim_querystring, '' )
: url_or_params;
}
return jq_deparam( url_or_params, coerce );
};
jq_deparam[ str_querystring ] = curry( jq_deparam_sub, 0 );
jq_deparam[ str_fragment ] = jq_deparam_fragment = curry( jq_deparam_sub, 1 );
// Section: Element manipulation
//
// Method: jQuery.elemUrlAttr
//
// Get the internal "Default URL attribute per tag" list, or augment the list
// with additional tag-attribute pairs, in case the defaults are insufficient.
//
// In the <jQuery.fn.querystring> and <jQuery.fn.fragment> methods, this list
// is used to determine which attribute contains the URL to be modified, if
// an "attr" param is not specified.
//
// Default Tag-Attribute List:
//
// a - href
// base - href
// iframe - src
// img - src
// input - src
// form - action
// link - href
// script - src
//
// Usage:
//
// > jQuery.elemUrlAttr( [ tag_attr ] );
//
// Arguments:
//
// tag_attr - (Object) An object containing a list of tag names and their
// associated default attribute names in the format { tag: 'attr', ... } to
// be merged into the internal tag-attribute list.
//
// Returns:
//
// (Object) An object containing all stored tag-attribute values.
// Only define function and set defaults if function doesn't already exist, as
// the urlInternal plugin will provide this method as well.
$[ str_elemUrlAttr ] || ($[ str_elemUrlAttr ] = function( obj ) {
return $.extend( elemUrlAttr_cache, obj );
})({
a: str_href,
base: str_href,
iframe: str_src,
img: str_src,
input: str_src,
form: 'action',
link: str_href,
script: str_src
});
jq_elemUrlAttr = $[ str_elemUrlAttr ];
// Method: jQuery.fn.querystring
//
// Update URL attribute in one or more elements, merging the current URL (with
// or without pre-existing query string params) plus any params object or
// string into a new URL, which is then set into that attribute. Like
// <jQuery.param.querystring (build url)>, but for all elements in a jQuery
// collection.
//
// Usage:
//
// > jQuery('selector').querystring( [ attr, ] params [, merge_mode ] );
//
// Arguments:
//
// attr - (String) Optional name of an attribute that will contain a URL to
// merge params or url into. See <jQuery.elemUrlAttr> for a list of default
// attributes.
// params - (Object) A params object to be merged into the URL attribute.
// params - (String) A URL containing query string params, or params string
// to be merged into the URL attribute.
// merge_mode - (Number) Merge behavior defaults to 0 if merge_mode is not
// specified, and is as-follows:
//
// * 0: params in the params argument will override any params in attr URL.
// * 1: any params in attr URL will override params in the params argument.
// * 2: params argument will completely replace any query string in attr
// URL.
//
// Returns:
//
// (jQuery) The initial jQuery collection of elements, but with modified URL
// attribute values.
// Method: jQuery.fn.fragment
//
// Update URL attribute in one or more elements, merging the current URL (with
// or without pre-existing fragment/hash params) plus any params object or
// string into a new URL, which is then set into that attribute. Like
// <jQuery.param.fragment (build url)>, but for all elements in a jQuery
// collection.
//
// Usage:
//
// > jQuery('selector').fragment( [ attr, ] params [, merge_mode ] );
//
// Arguments:
//
// attr - (String) Optional name of an attribute that will contain a URL to
// merge params into. See <jQuery.elemUrlAttr> for a list of default
// attributes.
// params - (Object) A params object to be merged into the URL attribute.
// params - (String) A URL containing fragment (hash) params, or params
// string to be merged into the URL attribute.
// merge_mode - (Number) Merge behavior defaults to 0 if merge_mode is not
// specified, and is as-follows:
//
// * 0: params in the params argument will override any params in attr URL.
// * 1: any params in attr URL will override params in the params argument.
// * 2: params argument will completely replace any fragment (hash) in attr
// URL.
//
// Returns:
//
// (jQuery) The initial jQuery collection of elements, but with modified URL
// attribute values.
function jq_fn_sub( mode, force_attr, params, merge_mode ) {
if ( !is_string( params ) && typeof params !== 'object' ) {
// force_attr not specified.
merge_mode = params;
params = force_attr;
force_attr = undefined;
}
return this.each(function(){
var that = $(this),
// Get attribute specified, or default specified via $.elemUrlAttr.
attr = force_attr || jq_elemUrlAttr()[ ( this.nodeName || '' ).toLowerCase() ] || '',
// Get URL value.
url = attr && that.attr( attr ) || '';
// Update attribute with new URL.
that.attr( attr, jq_param[ mode ]( url, params, merge_mode ) );
});
};
$.fn[ str_querystring ] = curry( jq_fn_sub, str_querystring );
$.fn[ str_fragment ] = curry( jq_fn_sub, str_fragment );
// Section: History, hashchange event
//
// Method: jQuery.bbq.pushState
//
// Adds a 'state' into the browser history at the current position, setting
// location.hash and triggering any bound <hashchange event> callbacks
// (provided the new state is different than the previous state).
//
// If no arguments are passed, an empty state is created, which is just a
// shortcut for jQuery.bbq.pushState( {}, 2 ).
//
// Usage:
//
// > jQuery.bbq.pushState( [ params [, merge_mode ] ] );
//
// Arguments:
//
// params - (String) A serialized params string or a hash string beginning
// with # to merge into location.hash.
// params - (Object) A params object to merge into location.hash.
// merge_mode - (Number) Merge behavior defaults to 0 if merge_mode is not
// specified (unless a hash string beginning with # is specified, in which
// case merge behavior defaults to 2), and is as-follows:
//
// * 0: params in the params argument will override any params in the
// current state.
// * 1: any params in the current state will override params in the params
// argument.
// * 2: params argument will completely replace current state.
//
// Returns:
//
// Nothing.
//
// Additional Notes:
//
// * Setting an empty state may cause the browser to scroll.
// * Unlike the fragment and querystring methods, if a hash string beginning
// with # is specified as the params agrument, merge_mode defaults to 2.
jq_bbq.pushState = jq_bbq_pushState = function( params, merge_mode ) {
if ( is_string( params ) && /^#/.test( params ) && merge_mode === undefined ) {
// Params string begins with # and merge_mode not specified, so completely
// overwrite window.location.hash.
merge_mode = 2;
}
var has_args = params !== undefined,
// Merge params into window.location using $.param.fragment.
url = jq_param_fragment( window[ str_location ][ str_href ],
has_args ? params : {}, has_args ? merge_mode : 2 );
// Set new window.location.href. If hash is empty, use just # to prevent
// browser from reloading the page. Note that Safari 3 & Chrome barf on
// location.hash = '#'.
window[ str_location ][ str_href ] = url + ( /#/.test( url ) ? '' : '#' );
};
// Method: jQuery.bbq.getState
//
// Retrieves the current 'state' from the browser history, parsing
// location.hash for a specific key or returning an object containing the
// entire state, optionally coercing numbers, booleans, null and undefined
// values.
//
// Usage:
//
// > jQuery.bbq.getState( [ key ] [, coerce ] );
//
// Arguments:
//
// key - (String) An optional state key for which to return a value.
// coerce - (Boolean) If true, coerces any numbers or true, false, null, and
// undefined to their actual value. Defaults to false.
//
// Returns:
//
// (Anything) If key is passed, returns the value corresponding with that key
// in the location.hash 'state', or undefined. If not, an object
// representing the entire 'state' is returned.
jq_bbq.getState = jq_bbq_getState = function( key, coerce ) {
return key === undefined || typeof key === 'boolean'
? jq_deparam_fragment( key ) // 'key' really means 'coerce' here
: jq_deparam_fragment( coerce )[ key ];
};
// Method: jQuery.bbq.removeState
//
// Remove one or more keys from the current browser history 'state', creating
// a new state, setting location.hash and triggering any bound
// <hashchange event> callbacks (provided the new state is different than
// the previous state).
//
// If no arguments are passed, an empty state is created, which is just a
// shortcut for jQuery.bbq.pushState( {}, 2 ).
//
// Usage:
//
// > jQuery.bbq.removeState( [ key [, key ... ] ] );
//
// Arguments:
//
// key - (String) One or more key values to remove from the current state,
// passed as individual arguments.
// key - (Array) A single array argument that contains a list of key values
// to remove from the current state.
//
// Returns:
//
// Nothing.
//
// Additional Notes:
//
// * Setting an empty state may cause the browser to scroll.
jq_bbq.removeState = function( arr ) {
var state = {};
// If one or more arguments is passed..
if ( arr !== undefined ) {
// Get the current state.
state = jq_bbq_getState();
// For each passed key, delete the corresponding property from the current
// state.
$.each( $.isArray( arr ) ? arr : arguments, function(i,v){
delete state[ v ];
});
}
// Set the state, completely overriding any existing state.
jq_bbq_pushState( state, 2 );
};
// Event: hashchange event (BBQ)
//
// Usage in jQuery 1.4 and newer:
//
// In jQuery 1.4 and newer, the event object passed into any hashchange event
// callback is augmented with a copy of the location.hash fragment at the time
// the event was triggered as its event.fragment property. In addition, the
// event.getState method operates on this property (instead of location.hash)
// which allows this fragment-as-a-state to be referenced later, even after
// window.location may have changed.
//
// Note that event.fragment and event.getState are not defined according to
// W3C (or any other) specification, but will still be available whether or
// not the hashchange event exists natively in the browser, because of the
// utility they provide.
//
// The event.fragment property contains the output of <jQuery.param.fragment>
// and the event.getState method is equivalent to the <jQuery.bbq.getState>
// method.
//
// > $(window).bind( 'hashchange', function( event ) {
// > var hash_str = event.fragment,
// > param_obj = event.getState(),
// > param_val = event.getState( 'param_name' ),
// > param_val_coerced = event.getState( 'param_name', true );
// > ...
// > });
//
// Usage in jQuery 1.3.2:
//
// In jQuery 1.3.2, the event object cannot to be augmented as in jQuery 1.4+,
// so the fragment state isn't bound to the event object and must instead be
// parsed using the <jQuery.param.fragment> and <jQuery.bbq.getState> methods.
//
// > $(window).bind( 'hashchange', function( event ) {
// > var hash_str = $.param.fragment(),
// > param_obj = $.bbq.getState(),
// > param_val = $.bbq.getState( 'param_name' ),
// > param_val_coerced = $.bbq.getState( 'param_name', true );
// > ...
// > });
//
// Additional Notes:
//
// * Due to changes in the special events API, jQuery BBQ v1.2 or newer is
// required to enable the augmented event object in jQuery 1.4.2 and newer.
// * See <jQuery hashchange event> for more detailed information.
jq_event_special[ str_hashchange ] = $.extend( jq_event_special[ str_hashchange ], {
// Augmenting the event object with the .fragment property and .getState
// method requires jQuery 1.4 or newer. Note: with 1.3.2, everything will
// work, but the event won't be augmented)
add: function( handleObj ) {
var old_handler;
function new_handler(e) {
// e.fragment is set to the value of location.hash (with any leading #
// removed) at the time the event is triggered.
var hash = e[ str_fragment ] = jq_param_fragment();
// e.getState() works just like $.bbq.getState(), but uses the
// e.fragment property stored on the event object.
e.getState = function( key, coerce ) {
return key === undefined || typeof key === 'boolean'
? jq_deparam( hash, key ) // 'key' really means 'coerce' here
: jq_deparam( hash, coerce )[ key ];
};
old_handler.apply( this, arguments );
};
// This may seem a little complicated, but it normalizes the special event
// .add method between jQuery 1.4/1.4.1 and 1.4.2+
if ( $.isFunction( handleObj ) ) {
// 1.4, 1.4.1
old_handler = handleObj;
return new_handler;
} else {
// 1.4.2+
old_handler = handleObj.handler;
handleObj.handler = new_handler;
}
}
});
})(jQuery,this);
/*!
* jQuery hashchange event - v1.2 - 2/11/2010
* http://benalman.com/projects/jquery-hashchange-plugin/
*
* Copyright (c) 2010 "Cowboy" Ben Alman
* Dual licensed under the MIT and GPL licenses.
* http://benalman.com/about/license/
*/
// Script: jQuery hashchange event
//
// *Version: 1.2, Last updated: 2/11/2010*
//
// Project Home - http://benalman.com/projects/jquery-hashchange-plugin/
// GitHub - http://github.com/cowboy/jquery-hashchange/
// Source - http://github.com/cowboy/jquery-hashchange/raw/master/jquery.ba-hashchange.js
// (Minified) - http://github.com/cowboy/jquery-hashchange/raw/master/jquery.ba-hashchange.min.js (1.1kb)
//
// About: License
//
// Copyright (c) 2010 "Cowboy" Ben Alman,
// Dual licensed under the MIT and GPL licenses.
// http://benalman.com/about/license/
//
// About: Examples
//
// This working example, complete with fully commented code, illustrate one way
// in which this plugin can be used.
//
// hashchange event - http://benalman.com/code/projects/jquery-hashchange/examples/hashchange/
//
// About: Support and Testing
//
// Information about what version or versions of jQuery this plugin has been
// tested with, what browsers it has been tested in, and where the unit tests
// reside (so you can test it yourself).
//
// jQuery Versions - 1.3.2, 1.4.1, 1.4.2
// Browsers Tested - Internet Explorer 6-8, Firefox 2-3.7, Safari 3-4, Chrome, Opera 9.6-10.1.
// Unit Tests - http://benalman.com/code/projects/jquery-hashchange/unit/
//
// About: Known issues
//
// While this jQuery hashchange event implementation is quite stable and robust,
// there are a few unfortunate browser bugs surrounding expected hashchange
// event-based behaviors, independent of any JavaScript window.onhashchange
// abstraction. See the following examples for more information:
//
// Chrome: Back Button - http://benalman.com/code/projects/jquery-hashchange/examples/bug-chrome-back-button/
// Firefox: Remote XMLHttpRequest - http://benalman.com/code/projects/jquery-hashchange/examples/bug-firefox-remote-xhr/
// WebKit: Back Button in an Iframe - http://benalman.com/code/projects/jquery-hashchange/examples/bug-webkit-hash-iframe/
// Safari: Back Button from a different domain - http://benalman.com/code/projects/jquery-hashchange/examples/bug-safari-back-from-diff-domain/
//
// About: Release History
//
// 1.2 - (2/11/2010) Fixed a bug where coming back to a page using this plugin
// from a page on another domain would cause an error in Safari 4. Also,
// IE6/7 Iframe is now inserted after the body (this actually works),
// which prevents the page from scrolling when the event is first bound.
// Event can also now be bound before DOM ready, but it won't be usable
// before then in IE6/7.
// 1.1 - (1/21/2010) Incorporated document.documentMode test to fix IE8 bug
// where browser version is incorrectly reported as 8.0, despite
// inclusion of the X-UA-Compatible IE=EmulateIE7 meta tag.
// 1.0 - (1/9/2010) Initial Release. Broke out the jQuery BBQ event.special
// window.onhashchange functionality into a separate plugin for users
// who want just the basic event & back button support, without all the
// extra awesomeness that BBQ provides. This plugin will be included as
// part of jQuery BBQ, but also be available separately.
(function($,window,undefined){
'$:nomunge'; // Used by YUI compressor.
// Method / object references.
var fake_onhashchange,
jq_event_special = $.event.special,
// Reused strings.
str_location = 'location',
str_hashchange = 'hashchange',
str_href = 'href',
// IE6/7 specifically need some special love when it comes to back-button
// support, so let's do a little browser sniffing..
browser = $.browser,
mode = document.documentMode,
is_old_ie = browser.msie && ( mode === undefined || mode < 8 ),
// Does the browser support window.onhashchange? Test for IE version, since
// IE8 incorrectly reports this when in "IE7" or "IE8 Compatibility View"!
supports_onhashchange = 'on' + str_hashchange in window && !is_old_ie;
// Get location.hash (or what you'd expect location.hash to be) sans any
// leading #. Thanks for making this necessary, Firefox!
function get_fragment( url ) {
url = url || window[ str_location ][ str_href ];
return url.replace( /^[^#]*#?(.*)$/, '$1' );
};
// Property: jQuery.hashchangeDelay
//
// The numeric interval (in milliseconds) at which the <hashchange event>
// polling loop executes. Defaults to 100.
$[ str_hashchange + 'Delay' ] = 100;
// Event: hashchange event
//
// Fired when location.hash changes. In browsers that support it, the native
// window.onhashchange event is used (IE8, FF3.6), otherwise a polling loop is
// initialized, running every <jQuery.hashchangeDelay> milliseconds to see if
// the hash has changed. In IE 6 and 7, a hidden Iframe is created to allow
// the back button and hash-based history to work.
//
// Usage:
//
// > $(window).bind( 'hashchange', function(e) {
// > var hash = location.hash;
// > ...
// > });
//
// Additional Notes:
//
// * The polling loop and Iframe are not created until at least one callback
// is actually bound to 'hashchange'.
// * If you need the bound callback(s) to execute immediately, in cases where
// the page 'state' exists on page load (via bookmark or page refresh, for
// example) use $(window).trigger( 'hashchange' );
// * The event can be bound before DOM ready, but since it won't be usable
// before then in IE6/7 (due to the necessary Iframe), recommended usage is
// to bind it inside a $(document).ready() callback.
jq_event_special[ str_hashchange ] = $.extend( jq_event_special[ str_hashchange ], {
// Called only when the first 'hashchange' event is bound to window.
setup: function() {
// If window.onhashchange is supported natively, there's nothing to do..
if ( supports_onhashchange ) { return false; }
// Otherwise, we need to create our own. And we don't want to call this
// until the user binds to the event, just in case they never do, since it
// will create a polling loop and possibly even a hidden Iframe.
$( fake_onhashchange.start );
},
// Called only when the last 'hashchange' event is unbound from window.
teardown: function() {
// If window.onhashchange is supported natively, there's nothing to do..
if ( supports_onhashchange ) { return false; }
// Otherwise, we need to stop ours (if possible).
$( fake_onhashchange.stop );
}
});
// fake_onhashchange does all the work of triggering the window.onhashchange
// event for browsers that don't natively support it, including creating a
// polling loop to watch for hash changes and in IE 6/7 creating a hidden
// Iframe to enable back and forward.
fake_onhashchange = (function(){
var self = {},
timeout_id,
iframe,
set_history,
get_history;
// Initialize. In IE 6/7, creates a hidden Iframe for history handling.
function init(){
// Most browsers don't need special methods here..
set_history = get_history = function(val){ return val; };
// But IE6/7 do!
if ( is_old_ie ) {
// Create hidden Iframe after the end of the body to prevent initial
// page load from scrolling unnecessarily.
iframe = $('<iframe src="javascript:0"/>').hide().insertAfter( 'body' )[0].contentWindow;
// Get history by looking at the hidden Iframe's location.hash.
get_history = function() {
return get_fragment( iframe.document[ str_location ][ str_href ] );
};
// Set a new history item by opening and then closing the Iframe
// document, *then* setting its location.hash.
set_history = function( hash, history_hash ) {
if ( hash !== history_hash ) {
var doc = iframe.document;
doc.open().close();
doc[ str_location ].hash = '#' + hash;
}
};
// Set initial history.
set_history( get_fragment() );
}
};
// Start the polling loop.
self.start = function() {
// Polling loop is already running!
if ( timeout_id ) { return; }
// Remember the initial hash so it doesn't get triggered immediately.
var last_hash = get_fragment();
// Initialize if not yet initialized.
set_history || init();
// This polling loop checks every $.hashchangeDelay milliseconds to see if
// location.hash has changed, and triggers the 'hashchange' event on
// window when necessary.
(function loopy(){
var hash = get_fragment(),
history_hash = get_history( last_hash );
if ( hash !== last_hash ) {
set_history( last_hash = hash, history_hash );
$(window).trigger( str_hashchange );
} else if ( history_hash !== last_hash ) {
window[ str_location ][ str_href ] = window[ str_location ][ str_href ].replace( /#.*/, '' ) + '#' + history_hash;
}
timeout_id = setTimeout( loopy, $[ str_hashchange + 'Delay' ] );
})();
};
// Stop the polling loop, but only if an IE6/7 Iframe wasn't created. In
// that case, even if there are no longer any bound event handlers, the
// polling loop is still necessary for back/next to work at all!
self.stop = function() {
if ( !iframe ) {
timeout_id && clearTimeout( timeout_id );
timeout_id = 0;
}
};
return self;
})();
})(jQuery,this); | JavaScript |
/*
* Metadata - jQuery plugin for parsing metadata from elements
*
* Copyright (c) 2006 John Resig, Yehuda Katz, J�örn Zaefferer, Paul McLanahan
*
* Dual licensed under the MIT and GPL licenses:
* http://www.opensource.org/licenses/mit-license.php
* http://www.gnu.org/licenses/gpl.html
*
* Revision: $Id: jquery.metadata.js 3640 2007-10-11 18:34:38Z pmclanahan $
*
*/
/**
* Sets the type of metadata to use. Metadata is encoded in JSON, and each property
* in the JSON will become a property of the element itself.
*
* There are four supported types of metadata storage:
*
* attr: Inside an attribute. The name parameter indicates *which* attribute.
*
* class: Inside the class attribute, wrapped in curly braces: { }
*
* elem: Inside a child element (e.g. a script tag). The
* name parameter indicates *which* element.
* html5: Values are stored in data-* attributes.
*
* The metadata for an element is loaded the first time the element is accessed via jQuery.
*
* As a result, you can define the metadata type, use $(expr) to load the metadata into the elements
* matched by expr, then redefine the metadata type and run another $(expr) for other elements.
*
* @name $.metadata.setType
*
* @example <p id="one" class="some_class {item_id: 1, item_label: 'Label'}">This is a p</p>
* @before $.metadata.setType("class")
* @after $("#one").metadata().item_id == 1; $("#one").metadata().item_label == "Label"
* @desc Reads metadata from the class attribute
*
* @example <p id="one" class="some_class" data="{item_id: 1, item_label: 'Label'}">This is a p</p>
* @before $.metadata.setType("attr", "data")
* @after $("#one").metadata().item_id == 1; $("#one").metadata().item_label == "Label"
* @desc Reads metadata from a "data" attribute
*
* @example <p id="one" class="some_class"><script>{item_id: 1, item_label: 'Label'}</script>This is a p</p>
* @before $.metadata.setType("elem", "script")
* @after $("#one").metadata().item_id == 1; $("#one").metadata().item_label == "Label"
* @desc Reads metadata from a nested script element
*
* @example <p id="one" class="some_class" data-item_id="1" data-item_label="Label">This is a p</p>
* @before $.metadata.setType("html5")
* @after $("#one").metadata().item_id == 1; $("#one").metadata().item_label == "Label"
* @desc Reads metadata from a series of data-* attributes
*
* @param String type The encoding type
* @param String name The name of the attribute to be used to get metadata (optional)
* @cat Plugins/Metadata
* @descr Sets the type of encoding to be used when loading metadata for the first time
* @type undefined
* @see metadata()
*/
(function($) {
$.extend({
metadata : {
defaults : {
type: 'class',
name: 'metadata',
cre: /({.*})/,
single: 'metadata'
},
setType: function( type, name ){
this.defaults.type = type;
this.defaults.name = name;
},
get: function( elem, opts ){
var settings = $.extend({},this.defaults,opts);
// check for empty string in single property
if ( !settings.single.length ) settings.single = 'metadata';
var data = $.data(elem, settings.single);
// returned cached data if it already exists
if ( data ) return data;
data = "{}";
var getData = function(data) {
if(typeof data != "string") return data;
if( data.indexOf('{') < 0 ) {
data = eval("(" + data + ")");
}
};
var getObject = function(data) {
if(typeof data != "string") return data;
data = eval("(" + data + ")");
return data;
};
if ( settings.type == "html5" ) {
var object = {};
$( elem.attributes ).each(function() {
var name = this.nodeName;
if(name.match(/^data-/)) name = name.replace(/^data-/, '');
else return true;
object[name] = getObject(this.nodeValue);
});
} else {
if ( settings.type == "class" ) {
var m = settings.cre.exec( elem.className );
if ( m )
data = m[1];
} else if ( settings.type == "elem" ) {
if( !elem.getElementsByTagName ) return;
var e = elem.getElementsByTagName(settings.name);
if ( e.length )
data = $.trim(e[0].innerHTML);
} else if ( elem.getAttribute != undefined ) {
var attr = elem.getAttribute( settings.name );
if ( attr )
data = attr;
}
object = getObject(data.indexOf("{") < 0 ? "{" + data + "}" : data);
}
$.data( elem, settings.single, object );
return object;
}
}
});
/**
* Returns the metadata object for the first member of the jQuery object.
*
* @name metadata
* @descr Returns element's metadata object
* @param Object opts An object contianing settings to override the defaults
* @type jQuery
* @cat Plugins/Metadata
*/
$.fn.metadata = function( opts ){
return $.metadata.get( this[0], opts );
};
})(jQuery); | JavaScript |
/**
* jQuery yiiactiveform plugin file.
*
* @author Qiang Xue <qiang.xue@gmail.com>
* @link http://www.yiiframework.com/
* @copyright Copyright © 2008-2010 Yii Software LLC
* @license http://www.yiiframework.com/license/
* @since 1.1.1
*/
(function ($) {
/*
* returns the value of the CActiveForm input field
* performs additional checks to get proper values for checkbox / radiobutton / checkBoxList / radioButtonList
* @param o object the jQuery object of the input element
*/
var getAFValue = function (o) {
var type,
c = [];
if (!o.length) {
return undefined;
}
if (o[0].tagName.toLowerCase() === 'span') {
o.find(':checked').each(function () {
c.push(this.value);
});
return c.join(',');
}
type = o.attr('type');
if (type === 'checkbox' || type === 'radio') {
return o.filter(':checked').val();
} else {
return o.val();
}
};
/**
* yiiactiveform set function.
* @param options map settings for the active form plugin. Please see {@link CActiveForm::options} for availablel options.
*/
$.fn.yiiactiveform = function (options) {
return this.each(function () {
var settings = $.extend({}, $.fn.yiiactiveform.defaults, options || {}),
$form = $(this);
if (settings.validationUrl === undefined) {
settings.validationUrl = $form.attr('action');
}
$.each(settings.attributes, function (i) {
this.value = getAFValue($form.find('#' + this.inputID));
settings.attributes[i] = $.extend({}, {
validationDelay: settings.validationDelay,
validateOnChange: settings.validateOnChange,
validateOnType: settings.validateOnType,
hideErrorMessage: settings.hideErrorMessage,
inputContainer: settings.inputContainer,
errorCssClass: settings.errorCssClass,
successCssClass: settings.successCssClass,
beforeValidateAttribute: settings.beforeValidateAttribute,
afterValidateAttribute: settings.afterValidateAttribute,
validatingCssClass: settings.validatingCssClass
}, this);
});
$form.data('settings', settings);
settings.submitting = false; // whether it is waiting for ajax submission result
var validate = function (attribute, forceValidate) {
if (forceValidate) {
attribute.status = 2;
}
$.each(settings.attributes, function () {
if (this.value !== getAFValue($form.find('#' + this.inputID))) {
this.status = 2;
forceValidate = true;
}
});
if (!forceValidate) {
return;
}
if (settings.timer !== undefined) {
clearTimeout(settings.timer);
}
settings.timer = setTimeout(function () {
if (settings.submitting || $form.is(':hidden')) {
return;
}
if (attribute.beforeValidateAttribute === undefined || attribute.beforeValidateAttribute($form, attribute)) {
$.each(settings.attributes, function () {
if (this.status === 2) {
this.status = 3;
$.fn.yiiactiveform.getInputContainer(this, $form).addClass(this.validatingCssClass);
}
});
$.fn.yiiactiveform.validate($form, function (data) {
var hasError = false;
$.each(settings.attributes, function () {
if (this.status === 2 || this.status === 3) {
hasError = $.fn.yiiactiveform.updateInput(this, data, $form) || hasError;
}
});
if (attribute.afterValidateAttribute !== undefined) {
attribute.afterValidateAttribute($form, attribute, data, hasError);
}
});
}
}, attribute.validationDelay);
};
$.each(settings.attributes, function (i, attribute) {
if (this.validateOnChange) {
$form.find('#' + this.inputID).change(function () {
validate(attribute, false);
}).blur(function () {
if (attribute.status !== 2 && attribute.status !== 3) {
validate(attribute, !attribute.status);
}
});
}
if (this.validateOnType) {
$form.find('#' + this.inputID).keyup(function () {
if (attribute.value !== getAFValue($(this))) {
validate(attribute, false);
}
});
}
});
if (settings.validateOnSubmit) {
$form.on('mouseup keyup', ':submit', function () {
$form.data('submitObject', $(this));
});
var validated = false;
$form.submit(function () {
if (validated) {
validated = false;
return true;
}
if (settings.timer !== undefined) {
clearTimeout(settings.timer);
}
settings.submitting = true;
if (settings.beforeValidate === undefined || settings.beforeValidate($form)) {
$.fn.yiiactiveform.validate($form, function (data) {
var hasError = false;
$.each(settings.attributes, function () {
hasError = $.fn.yiiactiveform.updateInput(this, data, $form) || hasError;
});
$.fn.yiiactiveform.updateSummary($form, data);
if (settings.afterValidate === undefined || settings.afterValidate($form, data, hasError)) {
if (!hasError) {
validated = true;
var $button = $form.data('submitObject') || $form.find(':submit:first');
// TODO: if the submission is caused by "change" event, it will not work
if ($button.length) {
$button.click();
} else { // no submit button in the form
$form.submit();
}
return;
}
}
settings.submitting = false;
});
} else {
settings.submitting = false;
}
return false;
});
}
/*
* In case of reseting the form we need to reset error messages
* NOTE1: $form.reset - does not exist
* NOTE2: $form.on('reset', ...) does not work
*/
$form.bind('reset', function () {
/*
* because we bind directly to a form reset event, not to a reset button (that could or could not exist),
* when this function is executed form elements values have not been reset yet,
* because of that we use the setTimeout
*/
setTimeout(function () {
$.each(settings.attributes, function () {
this.status = 0;
var $error = $form.find('#' + this.errorID),
$container = $.fn.yiiactiveform.getInputContainer(this, $form);
$container.removeClass(
this.validatingCssClass + ' ' +
this.errorCssClass + ' ' +
this.successCssClass
);
$error.html('').hide();
/*
* without the setTimeout() we would get here the current entered value before the reset instead of the reseted value
*/
this.value = getAFValue($form.find('#' + this.inputID));
});
/*
* If the form is submited (non ajax) with errors, labels and input gets the class 'error'
*/
$form.find('label, input').each(function () {
$(this).removeClass('error');
});
$('#' + settings.summaryID).hide().find('ul').html('');
//.. set to initial focus on reset
if (settings.focus !== undefined && !window.location.hash) {
$form.find(settings.focus).focus();
}
}, 1);
});
/*
* set to initial focus
*/
if (settings.focus !== undefined && !window.location.hash) {
$form.find(settings.focus).focus();
}
});
};
/**
* Returns the container element of the specified attribute.
* @param attribute object the configuration for a particular attribute.
* @param form the form jQuery object
* @return jQuery the jQuery representation of the container
*/
$.fn.yiiactiveform.getInputContainer = function (attribute, form) {
if (attribute.inputContainer === undefined) {
return form.find('#' + attribute.inputID).closest('div');
} else {
return form.find(attribute.inputContainer).filter(':has("#' + attribute.inputID + '")');
}
};
/**
* updates the error message and the input container for a particular attribute.
* @param attribute object the configuration for a particular attribute.
* @param messages array the json data obtained from the ajax validation request
* @param form the form jQuery object
* @return boolean whether there is a validation error for the specified attribute
*/
$.fn.yiiactiveform.updateInput = function (attribute, messages, form) {
attribute.status = 1;
var $error, $container,
hasError = false,
$el = form.find('#' + attribute.inputID);
if ($el.length) {
hasError = messages !== null && $.isArray(messages[attribute.id]) && messages[attribute.id].length > 0;
$error = form.find('#' + attribute.errorID);
$container = $.fn.yiiactiveform.getInputContainer(attribute, form);
$container.removeClass(
attribute.validatingCssClass + ' ' +
attribute.errorCssClass + ' ' +
attribute.successCssClass
);
if (hasError) {
$error.html(messages[attribute.id][0]);
$container.addClass(attribute.errorCssClass);
} else if (attribute.enableAjaxValidation || attribute.clientValidation) {
$container.addClass(attribute.successCssClass);
}
if (!attribute.hideErrorMessage) {
$error.toggle(hasError);
}
attribute.value = getAFValue($el);
}
return hasError;
};
/**
* updates the error summary, if any.
* @param form jquery the jquery representation of the form
* @param messages array the json data obtained from the ajax validation request
*/
$.fn.yiiactiveform.updateSummary = function (form, messages) {
var settings = $(form).data('settings'),
content = '';
if (settings.summaryID === undefined) {
return;
}
if (messages) {
$.each(settings.attributes, function () {
if ($.isArray(messages[this.id])) {
$.each(messages[this.id], function (j, message) {
content = content + '<li>' + message + '</li>';
});
}
});
}
$('#' + settings.summaryID).toggle(content !== '').find('ul').html(content);
};
/**
* Performs the ajax validation request.
* This method is invoked internally to trigger the ajax validation.
* @param form jquery the jquery representation of the form
* @param successCallback function the function to be invoked if the ajax request succeeds
* @param errorCallback function the function to be invoked if the ajax request fails
*/
$.fn.yiiactiveform.validate = function (form, successCallback, errorCallback) {
var $form = $(form),
settings = $form.data('settings'),
needAjaxValidation = false,
messages = {};
$.each(settings.attributes, function () {
var value,
msg = [];
if (this.clientValidation !== undefined && (settings.submitting || this.status === 2 || this.status === 3)) {
value = getAFValue($form.find('#' + this.inputID));
this.clientValidation(value, msg, this);
if (msg.length) {
messages[this.id] = msg;
}
}
if (this.enableAjaxValidation && !msg.length && (settings.submitting || this.status === 2 || this.status === 3)) {
needAjaxValidation = true;
}
});
if (!needAjaxValidation || settings.submitting && !$.isEmptyObject(messages)) {
if (settings.submitting) {
// delay callback so that the form can be submitted without problem
setTimeout(function () {
successCallback(messages);
}, 200);
} else {
successCallback(messages);
}
return;
}
var $button = $form.data('submitObject'),
extData = '&' + settings.ajaxVar + '=' + $form.attr('id');
if ($button && $button.length) {
extData += '&' + $button.attr('name') + '=' + $button.attr('value');
}
$.ajax({
url : settings.validationUrl,
type : $form.attr('method'),
data : $form.serialize() + extData,
dataType : 'json',
success : function (data) {
if (data !== null && typeof data === 'object') {
$.each(settings.attributes, function () {
if (!this.enableAjaxValidation) {
delete data[this.id];
}
});
successCallback($.extend({}, messages, data));
} else {
successCallback(messages);
}
},
error : function () {
if (errorCallback !== undefined) {
errorCallback();
}
}
});
};
/**
* Returns the configuration for the specified form.
* The configuration contains all needed information to perform ajax-based validation.
* @param form jquery the jquery representation of the form
* @return object the configuration for the specified form.
*/
$.fn.yiiactiveform.getSettings = function (form) {
return $(form).data('settings');
};
$.fn.yiiactiveform.defaults = {
ajaxVar: 'ajax',
validationUrl: undefined,
validationDelay: 200,
validateOnSubmit : false,
validateOnChange : true,
validateOnType : false,
hideErrorMessage : false,
inputContainer : undefined,
errorCssClass : 'error',
successCssClass : 'success',
validatingCssClass : 'validating',
summaryID : undefined,
timer: undefined,
beforeValidateAttribute: undefined, // function (form, attribute) : boolean
afterValidateAttribute: undefined, // function (form, attribute, data, hasError)
beforeValidate: undefined, // function (form) : boolean
afterValidate: undefined, // function (form, data, hasError) : boolean
/**
* list of attributes to be validated. Each array element is of the following structure:
* {
* id : 'ModelClass_attribute', // the unique attribute ID
* model : 'ModelClass', // the model class name
* name : 'name', // attribute name
* inputID : 'input-tag-id',
* errorID : 'error-tag-id',
* value : undefined,
* status : 0, // 0: empty, not entered before, 1: validated, 2: pending validation, 3: validating
* focus : undefined, // jquery selector that indicates which element to receive input focus initially
* validationDelay: 200,
* validateOnChange : true,
* validateOnType : false,
* hideErrorMessage : false,
* inputContainer : undefined,
* errorCssClass : 'error',
* successCssClass : 'success',
* validatingCssClass : 'validating',
* enableAjaxValidation : true,
* enableClientValidation : true,
* clientValidation : undefined, // function (value, messages, attribute) : client-side validation
* beforeValidateAttribute: undefined, // function (form, attribute) : boolean
* afterValidateAttribute: undefined, // function (form, attribute, data, hasError)
* }
*/
attributes : []
};
})(jQuery); | JavaScript |
/*
* Treeview 1.5pre - jQuery plugin to hide and show branches of a tree
*
* http://bassistance.de/jquery-plugins/jquery-plugin-treeview/
* http://docs.jquery.com/Plugins/Treeview
*
* Copyright (c) 2007 Jörn Zaefferer
*
* Dual licensed under the MIT and GPL licenses:
* http://www.opensource.org/licenses/mit-license.php
* http://www.gnu.org/licenses/gpl.html
*
* Revision: $Id: jquery.treeview.js 5759 2008-07-01 07:50:28Z joern.zaefferer $
*
*/
;(function($) {
// TODO rewrite as a widget, removing all the extra plugins
$.extend($.fn, {
swapClass: function(c1, c2) {
var c1Elements = this.filter('.' + c1);
this.filter('.' + c2).removeClass(c2).addClass(c1);
c1Elements.removeClass(c1).addClass(c2);
return this;
},
replaceClass: function(c1, c2) {
return this.filter('.' + c1).removeClass(c1).addClass(c2).end();
},
hoverClass: function(className) {
className = className || "hover";
return this.hover(function() {
$(this).addClass(className);
}, function() {
$(this).removeClass(className);
});
},
heightToggle: function(animated, callback) {
animated ?
this.animate({ height: "toggle" }, animated, callback) :
this.each(function(){
jQuery(this)[ jQuery(this).is(":hidden") ? "show" : "hide" ]();
if(callback)
callback.apply(this, arguments);
});
},
heightHide: function(animated, callback) {
if (animated) {
this.animate({ height: "hide" }, animated, callback);
} else {
this.hide();
if (callback)
this.each(callback);
}
},
prepareBranches: function(settings) {
if (!settings.prerendered) {
// mark last tree items
this.filter(":last-child:not(ul)").addClass(CLASSES.last);
// collapse whole tree, or only those marked as closed, anyway except those marked as open
this.filter((settings.collapsed ? "" : "." + CLASSES.closed) + ":not(." + CLASSES.open + ")").find(">ul").hide();
}
// return all items with sublists
return this.filter(":has(>ul)");
},
applyClasses: function(settings, toggler) {
// TODO use event delegation
this.filter(":has(>ul):not(:has(>a))").find(">span").unbind("click.treeview").bind("click.treeview", function(event) {
// don't handle click events on children, eg. checkboxes
if ( this == event.target )
toggler.apply($(this).next());
}).add( $("a", this) ).hoverClass();
if (!settings.prerendered) {
// handle closed ones first
this.filter(":has(>ul:hidden)")
.addClass(CLASSES.expandable)
.replaceClass(CLASSES.last, CLASSES.lastExpandable);
// handle open ones
this.not(":has(>ul:hidden)")
.addClass(CLASSES.collapsable)
.replaceClass(CLASSES.last, CLASSES.lastCollapsable);
// create hitarea if not present
var hitarea = this.find("div." + CLASSES.hitarea);
if (!hitarea.length)
hitarea = this.prepend("<div class=\"" + CLASSES.hitarea + "\"/>").find("div." + CLASSES.hitarea);
hitarea.removeClass().addClass(CLASSES.hitarea).each(function() {
var classes = "";
$.each($(this).parent().attr("class").split(" "), function() {
classes += this + "-hitarea ";
});
$(this).addClass( classes );
})
}
// apply event to hitarea
this.find("div." + CLASSES.hitarea).click( toggler );
},
treeview: function(settings) {
settings = $.extend({
cookieId: "treeview"
}, settings);
if ( settings.toggle ) {
var callback = settings.toggle;
settings.toggle = function() {
return callback.apply($(this).parent()[0], arguments);
};
}
// factory for treecontroller
function treeController(tree, control) {
// factory for click handlers
function handler(filter) {
return function() {
// reuse toggle event handler, applying the elements to toggle
// start searching for all hitareas
toggler.apply( $("div." + CLASSES.hitarea, tree).filter(function() {
// for plain toggle, no filter is provided, otherwise we need to check the parent element
return filter ? $(this).parent("." + filter).length : true;
}) );
return false;
};
}
// click on first element to collapse tree
$("a:eq(0)", control).click( handler(CLASSES.collapsable) );
// click on second to expand tree
$("a:eq(1)", control).click( handler(CLASSES.expandable) );
// click on third to toggle tree
$("a:eq(2)", control).click( handler() );
}
// handle toggle event
function toggler() {
$(this)
.parent()
// swap classes for hitarea
.find(">.hitarea")
.swapClass( CLASSES.collapsableHitarea, CLASSES.expandableHitarea )
.swapClass( CLASSES.lastCollapsableHitarea, CLASSES.lastExpandableHitarea )
.end()
// swap classes for parent li
.swapClass( CLASSES.collapsable, CLASSES.expandable )
.swapClass( CLASSES.lastCollapsable, CLASSES.lastExpandable )
// find child lists
.find( ">ul" )
// toggle them
.heightToggle( settings.animated, settings.toggle );
if ( settings.unique ) {
$(this).parent()
.siblings()
// swap classes for hitarea
.find(">.hitarea")
.replaceClass( CLASSES.collapsableHitarea, CLASSES.expandableHitarea )
.replaceClass( CLASSES.lastCollapsableHitarea, CLASSES.lastExpandableHitarea )
.end()
.replaceClass( CLASSES.collapsable, CLASSES.expandable )
.replaceClass( CLASSES.lastCollapsable, CLASSES.lastExpandable )
.find( ">ul" )
.heightHide( settings.animated, settings.toggle );
}
}
this.data("toggler", toggler);
function serialize() {
function binary(arg) {
return arg ? 1 : 0;
}
var data = [];
branches.each(function(i, e) {
data[i] = $(e).is(":has(>ul:visible)") ? 1 : 0;
});
$.cookie(settings.cookieId, data.join(""), settings.cookieOptions );
}
function deserialize() {
var stored = $.cookie(settings.cookieId);
if ( stored ) {
var data = stored.split("");
branches.each(function(i, e) {
$(e).find(">ul")[ parseInt(data[i]) ? "show" : "hide" ]();
});
}
}
// add treeview class to activate styles
this.addClass("treeview");
// prepare branches and find all tree items with child lists
var branches = this.find("li").prepareBranches(settings);
switch(settings.persist) {
case "cookie":
var toggleCallback = settings.toggle;
settings.toggle = function() {
serialize();
if (toggleCallback) {
toggleCallback.apply(this, arguments);
}
};
deserialize();
break;
case "location":
var current = this.find("a").filter(function() {
return this.href.toLowerCase() == location.href.toLowerCase();
});
if ( current.length ) {
// TODO update the open/closed classes
var items = current.addClass("selected").parents("ul, li").add( current.next() ).show();
if (settings.prerendered) {
// if prerendered is on, replicate the basic class swapping
items.filter("li")
.swapClass( CLASSES.collapsable, CLASSES.expandable )
.swapClass( CLASSES.lastCollapsable, CLASSES.lastExpandable )
.find(">.hitarea")
.swapClass( CLASSES.collapsableHitarea, CLASSES.expandableHitarea )
.swapClass( CLASSES.lastCollapsableHitarea, CLASSES.lastExpandableHitarea );
}
}
break;
}
branches.applyClasses(settings, toggler);
// if control option is set, create the treecontroller and show it
if ( settings.control ) {
treeController(this, settings.control);
$(settings.control).show();
}
return this;
}
});
// classes used by the plugin
// need to be styled via external stylesheet, see first example
$.treeview = {};
var CLASSES = ($.treeview.classes = {
open: "open",
closed: "closed",
expandable: "expandable",
expandableHitarea: "expandable-hitarea",
lastExpandableHitarea: "lastExpandable-hitarea",
collapsable: "collapsable",
collapsableHitarea: "collapsable-hitarea",
lastCollapsableHitarea: "lastCollapsable-hitarea",
lastCollapsable: "lastCollapsable",
lastExpandable: "lastExpandable",
last: "last",
hitarea: "hitarea"
});
})(jQuery); | JavaScript |
(function($) {
var CLASSES = $.treeview.classes;
var proxied = $.fn.treeview;
$.fn.treeview = function(settings) {
settings = $.extend({}, settings);
if (settings.add) {
return this.trigger("add", [settings.add]);
}
if (settings.remove) {
return this.trigger("remove", [settings.remove]);
}
return proxied.apply(this, arguments).bind("add", function(event, branches) {
$(branches).prev()
.removeClass(CLASSES.last)
.removeClass(CLASSES.lastCollapsable)
.removeClass(CLASSES.lastExpandable)
.find(">.hitarea")
.removeClass(CLASSES.lastCollapsableHitarea)
.removeClass(CLASSES.lastExpandableHitarea);
$(branches).find("li").andSelf().prepareBranches(settings).applyClasses(settings, $(this).data("toggler"));
}).bind("remove", function(event, branches) {
var prev = $(branches).prev();
var parent = $(branches).parent();
$(branches).remove();
prev.filter(":last-child").addClass(CLASSES.last)
.filter("." + CLASSES.expandable).replaceClass(CLASSES.last, CLASSES.lastExpandable).end()
.find(">.hitarea").replaceClass(CLASSES.expandableHitarea, CLASSES.lastExpandableHitarea).end()
.filter("." + CLASSES.collapsable).replaceClass(CLASSES.last, CLASSES.lastCollapsable).end()
.find(">.hitarea").replaceClass(CLASSES.collapsableHitarea, CLASSES.lastCollapsableHitarea);
if (parent.is(":not(:has(>))") && parent[0] != this) {
parent.parent().removeClass(CLASSES.collapsable).removeClass(CLASSES.expandable);
parent.siblings(".hitarea").andSelf().remove();
}
});
};
})(jQuery); | JavaScript |
/*! Copyright (c) 2010 Brandon Aaron (http://brandonaaron.net)
* Licensed under the MIT License (LICENSE.txt).
*
* Version 2.1.2
*/
(function($){
$.fn.bgiframe = ($.browser.msie && /msie 6\.0/i.test(navigator.userAgent) ? function(s) {
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 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 ( $(this).children('iframe.bgiframe').length === 0 )
this.insertBefore( document.createElement(html), this.firstChild );
});
} : function() { return this; });
// old alias
$.fn.bgIframe = $.fn.bgiframe;
function prop(n) {
return n && n.constructor === Number ? n + 'px' : n;
}
})(jQuery); | JavaScript |
/*
* Async Treeview 0.1 - Lazy-loading extension for Treeview
*
* http://bassistance.de/jquery-plugins/jquery-plugin-treeview/
*
* Copyright (c) 2007 Jörn Zaefferer
*
* Dual licensed under the MIT and GPL licenses:
* http://www.opensource.org/licenses/mit-license.php
* http://www.gnu.org/licenses/gpl.html
*
* Revision: $Id$
*
*/
;(function($) {
function load(settings, root, child, container) {
function createNode(parent) {
var current = $("<li/>").attr("id", this.id || "").html("<span>" + this.text + "</span>").appendTo(parent);
if (this.classes) {
current.children("span").addClass(this.classes);
}
if (this.expanded) {
current.addClass("open");
}
if (this.hasChildren || this.children && this.children.length) {
var branch = $("<ul/>").appendTo(current);
if (this.hasChildren) {
current.addClass("hasChildren");
createNode.call({
classes: "placeholder",
text: " ",
children:[]
}, branch);
}
if (this.children && this.children.length) {
$.each(this.children, createNode, [branch])
}
}
}
$.ajax($.extend(true, {
url: settings.url,
dataType: "json",
data: {
root: root
},
success: function(response) {
child.empty();
$.each(response, createNode, [child]);
$(container).treeview({add: child});
}
}, settings.ajax));
/*
$.getJSON(settings.url, {root: root}, function(response) {
function createNode(parent) {
var current = $("<li/>").attr("id", this.id || "").html("<span>" + this.text + "</span>").appendTo(parent);
if (this.classes) {
current.children("span").addClass(this.classes);
}
if (this.expanded) {
current.addClass("open");
}
if (this.hasChildren || this.children && this.children.length) {
var branch = $("<ul/>").appendTo(current);
if (this.hasChildren) {
current.addClass("hasChildren");
createNode.call({
classes: "placeholder",
text: " ",
children:[]
}, branch);
}
if (this.children && this.children.length) {
$.each(this.children, createNode, [branch])
}
}
}
child.empty();
$.each(response, createNode, [child]);
$(container).treeview({add: child});
});
*/
}
var proxied = $.fn.treeview;
$.fn.treeview = function(settings) {
if (!settings.url) {
return proxied.apply(this, arguments);
}
var container = this;
if (!container.children().size())
load(settings, "source", this, container);
var userToggle = settings.toggle;
return proxied.call(this, $.extend({}, settings, {
collapsed: true,
toggle: function() {
var $this = $(this);
if ($this.hasClass("hasChildren")) {
var childList = $this.removeClass("hasChildren").find("ul");
load(settings, this.id, childList, container);
}
if (userToggle) {
userToggle.apply(this, arguments);
}
}
}));
};
})(jQuery); | JavaScript |
/**
* jQuery Yii plugin file.
*
* @author Qiang Xue <qiang.xue@gmail.com>
* @link http://www.yiiframework.com/
* @copyright Copyright © 2008-2010 Yii Software LLC
* @license http://www.yiiframework.com/license/
*/
;(function($) {
$.extend($.fn, {
yiitab: function() {
function activate(id) {
var pos = id.indexOf("#");
if (pos>=0) {
id = id.substring(pos);
}
var $tab=$(id);
var $container=$tab.parent();
$container.find('>ul a').removeClass('active');
$container.find('>ul a[href="'+id+'"]').addClass('active');
$container.children('div').hide();
$tab.show();
}
this.find('>ul a').click(function(event) {
var href=$(this).attr('href');
var pos=href.indexOf('#');
activate(href);
if(pos==0 || (pos>0 && (window.location.pathname=='' || window.location.pathname==href.substring(0,pos))))
return false;
});
// activate a tab based on the current anchor
var url = decodeURI(window.location);
var pos = url.indexOf("#");
if (pos >= 0) {
var id = url.substring(pos);
if (this.find('>ul a[href="'+id+'"]').length > 0) {
activate(id);
return;
}
}
}
});
})(jQuery);
| JavaScript |
/**
* Cookie plugin
*
* Copyright (c) 2006 Klaus Hartl (stilbuero.de)
* Dual licensed under the MIT and GPL licenses:
* http://www.opensource.org/licenses/mit-license.php
* http://www.gnu.org/licenses/gpl.html
*
*/
/**
* Create a cookie with the given name and value and other optional parameters.
*
* @example $.cookie('the_cookie', 'the_value');
* @desc Set the value of a cookie.
* @example $.cookie('the_cookie', 'the_value', {expires: 7, path: '/', domain: 'jquery.com', secure: true});
* @desc Create a cookie with all available options.
* @example $.cookie('the_cookie', 'the_value');
* @desc Create a session cookie.
* @example $.cookie('the_cookie', null);
* @desc Delete a cookie by passing null as value.
*
* @param String name The name of the cookie.
* @param String value The value of the cookie.
* @param Object options An object literal containing key/value pairs to provide optional cookie attributes.
* @option Number|Date expires Either an integer specifying the expiration date from now on in days or a Date object.
* If a negative value is specified (e.g. a date in the past), the cookie will be deleted.
* If set to null or omitted, the cookie will be a session cookie and will not be retained
* when the the browser exits.
* @option String path The value of the path atribute of the cookie (default: path of page that created the cookie).
* @option String domain The value of the domain attribute of the cookie (default: domain of page that created the cookie).
* @option Boolean secure If true, the secure attribute of the cookie will be set and the cookie transmission will
* require a secure protocol (like HTTPS).
* @type undefined
*
* @name $.cookie
* @cat Plugins/Cookie
* @author Klaus Hartl/klaus.hartl@stilbuero.de
*/
/**
* Get the value of a cookie with the given name.
*
* @example $.cookie('the_cookie');
* @desc Get the value of a cookie.
*
* @param String name The name of the cookie.
* @return The value of the cookie.
* @type String
*
* @name $.cookie
* @cat Plugins/Cookie
* @author Klaus Hartl/klaus.hartl@stilbuero.de
*/
jQuery.cookie = function(name, value, options) {
if (typeof value != 'undefined') { // name and value given, set cookie
options = options || {};
if (value === null) {
value = '';
options.expires = -1;
}
var expires = '';
if (options.expires && (typeof options.expires == 'number' || options.expires.toUTCString)) {
var date;
if (typeof options.expires == 'number') {
date = new Date();
date.setTime(date.getTime() + (options.expires * 24 * 60 * 60 * 1000));
} else {
date = options.expires;
}
expires = '; expires=' + date.toUTCString(); // use expires attribute, max-age is not supported by IE
}
var path = options.path ? '; path=' + options.path : '';
var domain = options.domain ? '; domain=' + options.domain : '';
var secure = options.secure ? '; secure' : '';
document.cookie = [name, '=', encodeURIComponent(value), expires, path, domain, secure].join('');
} else { // only name given, get cookie
var cookieValue = null;
if (document.cookie && document.cookie != '') {
var cookies = document.cookie.split(';');
for (var i = 0; i < cookies.length; i++) {
var cookie = jQuery.trim(cookies[i]);
// Does this cookie string begin with the name we want?
if (cookie.substring(0, name.length + 1) == (name + '=')) {
cookieValue = decodeURIComponent(cookie.substring(name.length + 1));
break;
}
}
}
return cookieValue;
}
}; | JavaScript |
/*
Masked Input plugin for jQuery
Copyright (c) 2007-2011 Josh Bush (digitalbush.com)
Licensed under the MIT license (http://digitalbush.com/projects/masked-input-plugin/#license)
Version: 1.3
*/
(function($) {
var pasteEventName = ($.browser.msie ? 'paste' : 'input') + ".mask";
var iPhone = (window.orientation != undefined);
$.mask = {
//Predefined character definitions
definitions: {
'9': "[0-9]",
'a': "[A-Za-z]",
'*': "[A-Za-z0-9]"
},
dataName:"rawMaskFn"
};
$.fn.extend({
//Helper Function for Caret positioning
caret: function(begin, end) {
if (this.length == 0) return;
if (typeof begin == 'number') {
end = (typeof end == 'number') ? end : begin;
return this.each(function() {
if (this.setSelectionRange) {
this.setSelectionRange(begin, end);
} else if (this.createTextRange) {
var range = this.createTextRange();
range.collapse(true);
range.moveEnd('character', end);
range.moveStart('character', begin);
range.select();
}
});
} else {
if (this[0].setSelectionRange) {
begin = this[0].selectionStart;
end = this[0].selectionEnd;
} else if (document.selection && document.selection.createRange) {
var range = document.selection.createRange();
begin = 0 - range.duplicate().moveStart('character', -100000);
end = begin + range.text.length;
}
return { begin: begin, end: end };
}
},
unmask: function() { return this.trigger("unmask"); },
mask: function(mask, settings) {
if (!mask && this.length > 0) {
var input = $(this[0]);
return input.data($.mask.dataName)();
}
settings = $.extend({
placeholder: "_",
completed: null
}, settings);
var defs = $.mask.definitions;
var tests = [];
var partialPosition = mask.length;
var firstNonMaskPos = null;
var len = mask.length;
$.each(mask.split(""), function(i, c) {
if (c == '?') {
len--;
partialPosition = i;
} else if (defs[c]) {
tests.push(new RegExp(defs[c]));
if(firstNonMaskPos==null)
firstNonMaskPos = tests.length - 1;
} else {
tests.push(null);
}
});
return this.trigger("unmask").each(function() {
var input = $(this);
var buffer = $.map(mask.split(""), function(c, i) { if (c != '?') return defs[c] ? settings.placeholder : c });
var focusText = input.val();
function seekNext(pos) {
while (++pos <= len && !tests[pos]);
return pos;
};
function seekPrev(pos) {
while (--pos >= 0 && !tests[pos]);
return pos;
};
function shiftL(begin,end) {
if(begin<0)
return;
for (var i = begin,j = seekNext(end); i < len; i++) {
if (tests[i]) {
if (j < len && tests[i].test(buffer[j])) {
buffer[i] = buffer[j];
buffer[j] = settings.placeholder;
} else
break;
j = seekNext(j);
}
}
writeBuffer();
input.caret(Math.max(firstNonMaskPos, begin));
};
function shiftR(pos) {
for (var i = pos, c = settings.placeholder; i < len; i++) {
if (tests[i]) {
var j = seekNext(i);
var t = buffer[i];
buffer[i] = c;
if (j < len && tests[j].test(t))
c = t;
else
break;
}
}
};
function keydownEvent(e) {
var k=e.which;
//backspace, delete, and escape get special treatment
if(k == 8 || k == 46 || (iPhone && k == 127)){
var pos = input.caret(),
begin = pos.begin,
end = pos.end;
if(end-begin==0){
begin=k!=46?seekPrev(begin):(end=seekNext(begin-1));
end=k==46?seekNext(end):end;
}
clearBuffer(begin, end);
shiftL(begin,end-1);
return false;
} else if (k == 27) {//escape
input.val(focusText);
input.caret(0, checkVal());
return false;
}
};
function keypressEvent(e) {
var k = e.which,
pos = input.caret();
if (e.ctrlKey || e.altKey || e.metaKey || k<32) {//Ignore
return true;
} else if (k) {
if(pos.end-pos.begin!=0){
clearBuffer(pos.begin, pos.end);
shiftL(pos.begin, pos.end-1);
}
var p = seekNext(pos.begin - 1);
if (p < len) {
var c = String.fromCharCode(k);
if (tests[p].test(c)) {
shiftR(p);
buffer[p] = c;
writeBuffer();
var next = seekNext(p);
input.caret(next);
if (settings.completed && next >= len)
settings.completed.call(input);
}
}
return false;
}
};
function clearBuffer(start, end) {
for (var i = start; i < end && i < len; i++) {
if (tests[i])
buffer[i] = settings.placeholder;
}
};
function writeBuffer() { return input.val(buffer.join('')).val(); };
function checkVal(allow) {
//try to place characters where they belong
var test = input.val();
var lastMatch = -1;
for (var i = 0, pos = 0; i < len; i++) {
if (tests[i]) {
buffer[i] = settings.placeholder;
while (pos++ < test.length) {
var c = test.charAt(pos - 1);
if (tests[i].test(c)) {
buffer[i] = c;
lastMatch = i;
break;
}
}
if (pos > test.length)
break;
} else if (buffer[i] == test.charAt(pos) && i!=partialPosition) {
pos++;
lastMatch = i;
}
}
if (!allow && lastMatch + 1 < partialPosition) {
input.val("");
clearBuffer(0, len);
} else if (allow || lastMatch + 1 >= partialPosition) {
writeBuffer();
if (!allow) input.val(input.val().substring(0, lastMatch + 1));
}
return (partialPosition ? i : firstNonMaskPos);
};
input.data($.mask.dataName,function(){
return $.map(buffer, function(c, i) {
return tests[i]&&c!=settings.placeholder ? c : null;
}).join('');
})
if (!input.attr("readonly"))
input
.one("unmask", function() {
input
.unbind(".mask")
.removeData($.mask.dataName);
})
.bind("focus.mask", function() {
focusText = input.val();
var pos = checkVal();
writeBuffer();
var moveCaret=function(){
if (pos == mask.length)
input.caret(0, pos);
else
input.caret(pos);
};
($.browser.msie ? moveCaret:function(){setTimeout(moveCaret,0)})();
})
.bind("blur.mask", function() {
checkVal();
if (input.val() != focusText)
input.change();
})
.bind("keydown.mask", keydownEvent)
.bind("keypress.mask", keypressEvent)
.bind(pasteEventName, function() {
setTimeout(function() { input.caret(checkVal(true)); }, 0);
});
checkVal(); //Perform initial check for existing values
});
}
});
})(jQuery);
| JavaScript |
/*! http://mths.be/punycode by @mathias */
;(function(root) {
/**
* The `punycode` object.
* @name punycode
* @type Object
*/
var punycode,
/** Detect free variables `define`, `exports`, `module` and `require` */
freeDefine = typeof define == 'function' && typeof define.amd == 'object' &&
define.amd && define,
freeExports = typeof exports == 'object' && exports,
freeModule = typeof module == 'object' && module,
freeRequire = typeof require == 'function' && require,
/** Highest positive signed 32-bit float value */
maxInt = 2147483647, // aka. 0x7FFFFFFF or 2^31-1
/** Bootstring parameters */
base = 36,
tMin = 1,
tMax = 26,
skew = 38,
damp = 700,
initialBias = 72,
initialN = 128, // 0x80
delimiter = '-', // '\x2D'
/** Regular expressions */
regexNonASCII = /[^ -~]/, // unprintable ASCII chars + non-ASCII chars
regexPunycode = /^xn--/,
/** Error messages */
errors = {
'overflow': 'Overflow: input needs wider integers to process.',
'not-basic': 'Illegal input >= 0x80 (not a basic code point)',
'invalid-input': 'Invalid input'
},
/** Convenience shortcuts */
baseMinusTMin = base - tMin,
floor = Math.floor,
stringFromCharCode = String.fromCharCode,
/** Temporary variable */
key;
/*--------------------------------------------------------------------------*/
/**
* A generic error utility function.
* @private
* @param {String} type The error type.
* @returns {Error} Throws a `RangeError` with the applicable error message.
*/
function error(type) {
throw RangeError(errors[type]);
}
/**
* A generic `Array#map` utility function.
* @private
* @param {Array} array The array to iterate over.
* @param {Function} callback The function that gets called for every array
* item.
* @returns {Array} A new array of values returned by the callback function.
*/
function map(array, fn) {
var length = array.length;
while (length--) {
array[length] = fn(array[length]);
}
return array;
}
/**
* A simple `Array#map`-like wrapper to work with domain name strings.
* @private
* @param {String} domain The domain name.
* @param {Function} callback The function that gets called for every
* character.
* @returns {Array} A new string of characters returned by the callback
* function.
*/
function mapDomain(string, fn) {
var glue = '.';
return map(string.split(glue), fn).join(glue);
}
/**
* Creates an array containing the decimal code points of each Unicode
* character in the string. While JavaScript uses UCS-2 internally,
* this function will convert a pair of surrogate halves (each of which
* UCS-2 exposes as separate characters) into a single code point,
* matching UTF-16.
* @see `punycode.ucs2.encode`
* @see <http://mathiasbynens.be/notes/javascript-encoding>
* @memberOf punycode.ucs2
* @name decode
* @param {String} string The Unicode input string (UCS-2).
* @returns {Array} The new array of code points.
*/
function ucs2decode(string) {
var output = [],
counter = 0,
length = string.length,
value,
extra;
while (counter < length) {
value = string.charCodeAt(counter++);
if ((value & 0xF800) == 0xD800 && counter < length) {
// high surrogate, and there is a next character
extra = string.charCodeAt(counter++);
if ((extra & 0xFC00) == 0xDC00) { // low surrogate
output.push(((value & 0x3FF) << 10) + (extra & 0x3FF) + 0x10000);
} else {
output.push(value, extra);
}
} else {
output.push(value);
}
}
return output;
}
/**
* Creates a string based on an array of decimal code points.
* @see `punycode.ucs2.decode`
* @memberOf punycode.ucs2
* @name encode
* @param {Array} codePoints The array of decimal code points.
* @returns {String} The new Unicode string (UCS-2).
*/
function ucs2encode(array) {
return map(array, function(value) {
var output = '';
if (value > 0xFFFF) {
value -= 0x10000;
output += stringFromCharCode(value >>> 10 & 0x3FF | 0xD800);
value = 0xDC00 | value & 0x3FF;
}
output += stringFromCharCode(value);
return output;
}).join('');
}
/**
* Converts a basic code point into a digit/integer.
* @see `digitToBasic()`
* @private
* @param {Number} codePoint The basic (decimal) code point.
* @returns {Number} The numeric value of a basic code point (for use in
* representing integers) in the range `0` to `base - 1`, or `base` if
* the code point does not represent a value.
*/
function basicToDigit(codePoint) {
return codePoint - 48 < 10
? codePoint - 22
: codePoint - 65 < 26
? codePoint - 65
: codePoint - 97 < 26
? codePoint - 97
: base;
}
/**
* Converts a digit/integer into a basic code point.
* @see `basicToDigit()`
* @private
* @param {Number} digit The numeric value of a basic code point.
* @returns {Number} The basic code point whose value (when used for
* representing integers) is `digit`, which needs to be in the range
* `0` to `base - 1`. If `flag` is non-zero, the uppercase form is
* used; else, the lowercase form is used. The behavior is undefined
* if flag is non-zero and `digit` has no uppercase form.
*/
function digitToBasic(digit, flag) {
// 0..25 map to ASCII a..z or A..Z
// 26..35 map to ASCII 0..9
return digit + 22 + 75 * (digit < 26) - ((flag != 0) << 5);
}
/**
* Bias adaptation function as per section 3.4 of RFC 3492.
* http://tools.ietf.org/html/rfc3492#section-3.4
* @private
*/
function adapt(delta, numPoints, firstTime) {
var k = 0;
delta = firstTime ? floor(delta / damp) : delta >> 1;
delta += floor(delta / numPoints);
for (/* no initialization */; delta > baseMinusTMin * tMax >> 1; k += base) {
delta = floor(delta / baseMinusTMin);
}
return floor(k + (baseMinusTMin + 1) * delta / (delta + skew));
}
/**
* Converts a basic code point to lowercase is `flag` is falsy, or to
* uppercase if `flag` is truthy. The code point is unchanged if it's
* caseless. The behavior is undefined if `codePoint` is not a basic code
* point.
* @private
* @param {Number} codePoint The numeric value of a basic code point.
* @returns {Number} The resulting basic code point.
*/
function encodeBasic(codePoint, flag) {
codePoint -= (codePoint - 97 < 26) << 5;
return codePoint + (!flag && codePoint - 65 < 26) << 5;
}
/**
* Converts a Punycode string of ASCII code points to a string of Unicode
* code points.
* @memberOf punycode
* @param {String} input The Punycode string of ASCII code points.
* @returns {String} The resulting string of Unicode code points.
*/
function decode(input) {
// Don't use UCS-2
var output = [],
inputLength = input.length,
out,
i = 0,
n = initialN,
bias = initialBias,
basic,
j,
index,
oldi,
w,
k,
digit,
t,
length,
/** Cached calculation results */
baseMinusT;
// Handle the basic code points: let `basic` be the number of input code
// points before the last delimiter, or `0` if there is none, then copy
// the first basic code points to the output.
basic = input.lastIndexOf(delimiter);
if (basic < 0) {
basic = 0;
}
for (j = 0; j < basic; ++j) {
// if it's not a basic code point
if (input.charCodeAt(j) >= 0x80) {
error('not-basic');
}
output.push(input.charCodeAt(j));
}
// Main decoding loop: start just after the last delimiter if any basic code
// points were copied; start at the beginning otherwise.
for (index = basic > 0 ? basic + 1 : 0; index < inputLength; /* no final expression */) {
// `index` is the index of the next character to be consumed.
// Decode a generalized variable-length integer into `delta`,
// which gets added to `i`. The overflow checking is easier
// if we increase `i` as we go, then subtract off its starting
// value at the end to obtain `delta`.
for (oldi = i, w = 1, k = base; /* no condition */; k += base) {
if (index >= inputLength) {
error('invalid-input');
}
digit = basicToDigit(input.charCodeAt(index++));
if (digit >= base || digit > floor((maxInt - i) / w)) {
error('overflow');
}
i += digit * w;
t = k <= bias ? tMin : (k >= bias + tMax ? tMax : k - bias);
if (digit < t) {
break;
}
baseMinusT = base - t;
if (w > floor(maxInt / baseMinusT)) {
error('overflow');
}
w *= baseMinusT;
}
out = output.length + 1;
bias = adapt(i - oldi, out, oldi == 0);
// `i` was supposed to wrap around from `out` to `0`,
// incrementing `n` each time, so we'll fix that now:
if (floor(i / out) > maxInt - n) {
error('overflow');
}
n += floor(i / out);
i %= out;
// Insert `n` at position `i` of the output
output.splice(i++, 0, n);
}
return ucs2encode(output);
}
/**
* Converts a string of Unicode code points to a Punycode string of ASCII
* code points.
* @memberOf punycode
* @param {String} input The string of Unicode code points.
* @returns {String} The resulting Punycode string of ASCII code points.
*/
function encode(input) {
var n,
delta,
handledCPCount,
basicLength,
bias,
j,
m,
q,
k,
t,
currentValue,
output = [],
/** `inputLength` will hold the number of code points in `input`. */
inputLength,
/** Cached calculation results */
handledCPCountPlusOne,
baseMinusT,
qMinusT;
// Convert the input in UCS-2 to Unicode
input = ucs2decode(input);
// Cache the length
inputLength = input.length;
// Initialize the state
n = initialN;
delta = 0;
bias = initialBias;
// Handle the basic code points
for (j = 0; j < inputLength; ++j) {
currentValue = input[j];
if (currentValue < 0x80) {
output.push(stringFromCharCode(currentValue));
}
}
handledCPCount = basicLength = output.length;
// `handledCPCount` is the number of code points that have been handled;
// `basicLength` is the number of basic code points.
// Finish the basic string - if it is not empty - with a delimiter
if (basicLength) {
output.push(delimiter);
}
// Main encoding loop:
while (handledCPCount < inputLength) {
// All non-basic code points < n have been handled already. Find the next
// larger one:
for (m = maxInt, j = 0; j < inputLength; ++j) {
currentValue = input[j];
if (currentValue >= n && currentValue < m) {
m = currentValue;
}
}
// Increase `delta` enough to advance the decoder's <n,i> state to <m,0>,
// but guard against overflow
handledCPCountPlusOne = handledCPCount + 1;
if (m - n > floor((maxInt - delta) / handledCPCountPlusOne)) {
error('overflow');
}
delta += (m - n) * handledCPCountPlusOne;
n = m;
for (j = 0; j < inputLength; ++j) {
currentValue = input[j];
if (currentValue < n && ++delta > maxInt) {
error('overflow');
}
if (currentValue == n) {
// Represent delta as a generalized variable-length integer
for (q = delta, k = base; /* no condition */; k += base) {
t = k <= bias ? tMin : (k >= bias + tMax ? tMax : k - bias);
if (q < t) {
break;
}
qMinusT = q - t;
baseMinusT = base - t;
output.push(
stringFromCharCode(digitToBasic(t + qMinusT % baseMinusT, 0))
);
q = floor(qMinusT / baseMinusT);
}
output.push(stringFromCharCode(digitToBasic(q, 0)));
bias = adapt(delta, handledCPCountPlusOne, handledCPCount == basicLength);
delta = 0;
++handledCPCount;
}
}
++delta;
++n;
}
return output.join('');
}
/**
* Converts a Punycode string representing a domain name to Unicode. Only the
* Punycoded parts of the domain name will be converted, i.e. it doesn't
* matter if you call it on a string that has already been converted to
* Unicode.
* @memberOf punycode
* @param {String} domain The Punycode domain name to convert to Unicode.
* @returns {String} The Unicode representation of the given Punycode
* string.
*/
function toUnicode(domain) {
return mapDomain(domain, function(string) {
return regexPunycode.test(string)
? decode(string.slice(4).toLowerCase())
: string;
});
}
/**
* Converts a Unicode string representing a domain name to Punycode. Only the
* non-ASCII parts of the domain name will be converted, i.e. it doesn't
* matter if you call it with a domain that's already in ASCII.
* @memberOf punycode
* @param {String} domain The domain name to convert, as a Unicode string.
* @returns {String} The Punycode representation of the given domain name.
*/
function toASCII(domain) {
return mapDomain(domain, function(string) {
return regexNonASCII.test(string)
? 'xn--' + encode(string)
: string;
});
}
/*--------------------------------------------------------------------------*/
/** Define the public API */
punycode = {
/**
* A string representing the current Punycode.js version number.
* @memberOf punycode
* @type String
*/
'version': '1.1.1',
/**
* An object of methods to convert from JavaScript's internal character
* representation (UCS-2) to decimal Unicode code points, and back.
* @see <http://mathiasbynens.be/notes/javascript-encoding>
* @memberOf punycode
* @type Object
*/
'ucs2': {
'decode': ucs2decode,
'encode': ucs2encode
},
'decode': decode,
'encode': encode,
'toASCII': toASCII,
'toUnicode': toUnicode
};
/** Expose `punycode` */
if (freeExports) {
if (freeModule && freeModule.exports == freeExports) {
// in Node.js or Ringo 0.8+
freeModule.exports = punycode;
} else {
// in Narwhal or Ringo 0.7-
for (key in punycode) {
punycode.hasOwnProperty(key) && (freeExports[key] = punycode[key]);
}
}
} else if (freeDefine) {
// via curl.js or RequireJS
define('punycode', punycode);
} else {
// in a browser or Rhino
root.punycode = punycode;
}
}(this)); | JavaScript |
window.addEventListener("keydown", moveSomething, false);
function moveSomething(e) {
switch(e.keyCode) {
case 37:
// left key pressed
window.location.href = "/game/?dir=3";
break;
case 38:
// up key pressed
window.location.href = "/game/?dir=1";
break;
case 39:
// right key pressed
window.location.href = "/game/?dir=2";
break;
case 40:
// down key pressed
window.location.href = "/game/?dir=4";
break;
case 13:
//new game
window.location.href = "/game/?dir=0";
break;
}
} | JavaScript |
statistikk.prototype.hentXMLHTTP = function() {
var xmlHttp;
try {
xmlHttp = new ActiveXObject("Msxml2.XMLHTTP"); // For Old Microsoft
// Browsers
} catch (e) {
try {
xmlHttp = new ActiveXObject("Microsoft.XMLHTTP"); // For
// Microsoft
// IE 6.0+
} catch (e2) {
xmlHttp = false; // No Browser accepts the XMLHTTP Object then
// false
}
}
if (!xmlHttp && typeof XMLHttpRequest != 'undefined') {
xmlHttp = new XMLHttpRequest(); // For Mozilla, Opera Browsers
}
return xmlHttp;
};
statistikk.prototype.ajaxSendStatistikk = function(s) {
var xmlHttp = s.hentXMLHTTP();
if (xmlHttp) {
var JSONString = JSON.stringify(s);
xmlHttp.open("POST", "KlientLeggInn", true);
xmlHttp.setRequestHeader('Content-Type',
'application/x-www-form-urlencoded');
xmlHttp.send(JSONString);
}
};
function statistikk() {
this.browserName;
this.OSName;
this.screenRes;
this.winRes;
this.fargeDybde;
this.posisjon;
}
statistikk.prototype.finnBrowser = function(s) {
var nAgt = navigator.userAgent;
var nameOffset, verOffset;
var fullVersion = '' + parseFloat(navigator.appVersion);
s.browserName = navigator.appName;
if ((verOffset = nAgt.indexOf("Opera")) != -1) {
s.browserName = "Opera";
fulllVersion = n.Agt.substring(verOffset + 6);
if ((verOffset = nAgt.indexOf("Version")) != -1)
s.fullVersion = nAgt.substring(verOffset + 8);
}
// In MSIE, the true version is after "MSIE" in userAgent
else if ((verOffset = nAgt.indexOf("MSIE")) != -1) {
s.browserName = "Microsoft Internet Explorer";
fullVersion = nAgt.substring(verOffset + 5);
}
// In Chrome, the true version is after "Chrome"
else if ((verOffset = nAgt.indexOf("Chrome")) != -1) {
s.browserName = "Chrome";
fullVersion = nAgt.substring(verOffset + 7);
}
// In Safari, the true version is after "Safari" or after "Version"
else if ((verOffset = nAgt.indexOf("Safari")) != -1) {
s.browserName = "Safari";
fullVersion = nAgt.substring(verOffset + 7);
if ((verOffset = nAgt.indexOf("Version")) != -1)
fullVersion = nAgt.substring(verOffset + 8);
}
// In Firefox, the true version is after "Firefox"
else if ((verOffset = nAgt.indexOf("Firefox")) != -1) {
s.browserName = "Firefox";
fullVersion = nAgt.substring(verOffset + 8);
} else if ((nameOffset = nAgt.lastIndexOf(' ') + 1) < (verOffset = nAgt
.lastIndexOf('/'))) {
s.browserName = nAgt.substring(nameOffset, verOffset);
fullVersion = nAgt.substring(verOffset + 1);
if (browserName.toLowerCase() == browserName.toUpperCase()) {
s.browserName = navigator.appName;
}
}
s.browserName = s.browserName + " " + fullVersion;
return s;
};
statistikk.prototype.finnOperativSystem = function(s) {
s.OSName = "Ukjent OS";
if (navigator.appVersion.indexOf("Win") != -1) {
s.OSName = "Windows";
}
if (navigator.appVersion.indexOf("Mac") != -1) {
s.OSName = "MacOS";
}
if (navigator.appVersion.indexOf("X11") != -1) {
s.OSName = "UNIX";
}
if (navigator.appVersion.indexOf("Linux") != -1) {
s.OSName = "Linux";
}
return s;
};
statistikk.prototype.finnSkjermStorleik = function(s) {
var screenW = 640;
var screenH = 480;
if (parseInt(navigator.appVersion) > 3) {
screenW = screen.width;
screenH = screen.height;
s.screenRes = screenW + "x" + screenH;
} else if (navigator.appName == "Netscape"
&& parseInt(navigator.appVersion) == 3 && navigator.javaEnabled()) {
var jToolkit = java.awt.Tollkit.getDefaultToolkit();
var jScreenSize = jToolkit.getScreenSize();
screenW = jScreenSize.width;
screenH = jScreenSize.height;
s.screenRes = screenW + "x" + screenH;
}
return s;
};
statistikk.prototype.finnVinduStorleik = function(s) {
var winW = 630;
var winH = 460;
if (document.body && document.body.offsetWidth) {
winW = document.body.offsetWidth;
winH = document.body.offsetHeight;
s.winRes = winW + "x" + winH;
}
if (document.compatMode == 'CSS1Compat' && document.documentElement
&& document.documentElement.offsetWidth) {
winW = document.documentElement.offsetWidth;
winH = document.documentElement.offsetHeight;
s.winRes = winW + "x" + winH;
}
if (window.innerWidth && window.innerHeight) {
winW = window.innerWidth;
winH = window.innerHeight;
s.winRes = winW + "x" + winH;
}
return s;
};
statistikk.prototype.finnFargeD = function(s) {
var screenObj = window.screen;
s.fargedybde = screenObj.colorDepth;
return s;
};
statistikk.prototype.finnPosisjon = function(s) {
var venstre;
var hoyre;
if (s.browserName.indexOf("Internet Explorer") == -1) {
venstre = window.screenX;
hoyre = window.screenY;
} else {
venstre = window.screenLeft;
hoyre = window.screenTop;
}
s.posisjon = "Venstre: " + venstre + ", Topp: " + hoyre;
return s;
}; | JavaScript |
function Medlem() {
this.medlemId;
this.fornavn;
this.etternavn;
this.adresse;
this.tlf;
}
function Medlemslisteobjekt() {
this.medlemsliste = new Array();
this.loggId = -1;
//this.t;
}
function RegelmessigObjekt(){
this.t=null;
}
RegelmessigObjekt.prototype.startRegelmessigAjax = function(){
this.t = setTimeout(medlemObjekt.ajaxHentEndringer,1000);
};
RegelmessigObjekt.prototype.stopRegelmessig = function() {
clearTimeout(this.t);
};
var medlemObjekt = new Medlemslisteobjekt();
var regelmessig = new RegelmessigObjekt();
function HTTPObjekt() {
/* Oppretter objektet som skal kommunisere med webtjener */
if (typeof window.XMLHttpRequest != "undefined") { // Firefox, Opera,
// Safari, etc
return new XMLHttpRequest();
}
if (typeof window.ActiveXObject == "function") { // IE5 og IE6
try {
return new ActiveXObject("Msxml2.XMLHTTP");
} catch (e) {
try {
return new ActiveXObject("Microsoft.XMLHTTP");
} catch (e) {;
};
};
}
return false;
}
Medlemslisteobjekt.prototype.handleServerResponse = function(xmlHttp) {
// alert("handleserverresp");
if (xmlHttp && xmlHttp.readyState == 4) {
if (xmlHttp.status == 200) {
regelmessig.startRegelmessigAjax();
var response = JSON.parse(xmlHttp.responseText.split(","));
// element
this.loggId = response.loggId;
if (response.nyeMedlemmer != null) {
for ( var i = 0; i < response.nyeMedlemmer.length; i++) {
var m = new Medlem();
m.fornavn = response.nyeMedlemmer[i].fornavn;
m.etternavn = response.nyeMedlemmer[i].etternavn;
m.adresse = response.nyeMedlemmer[i].adresse;
m.tlf = response.nyeMedlemmer[i].telefon;
m.medlemId = response.nyeMedlemmer[i].medlemId;
this.medlemsliste.push(m);
};
}
if (response.slettedeMedlemmer
&& response.slettedeMedlemmer.length > 0) {
for ( var i = 0; i < response.slettedeMedlemmer.length; i++) {
var id = response.slettedeMedlemmer[i];
for ( var j = 0; j < this.medlemsliste.length; j++) {
var medlemj = this.medlemsliste[j];
if (medlemj.medlemId == id) {
this.medlemsliste.splice(j, 1);
};
};
};
}
if (response.endredeMedlemmer) {
for ( var i = 0; i < response.endredeMedlemmer.length; i++) {
var medlemi = response.endredeMedlemmer[i];
for ( var j = 0; j < this.medlemsliste.length; j++) {
var medlemj = this.medlemsliste[j];
if (medlemj.medlemId == medlemi.medlemId) {
this.medlemsliste[j].fornavn = medlemi.fornavn;
this.medlemsliste[j].etternavn = medlemi.etternavn;
this.medlemsliste[j].adresse = medlemi.adresse;
this.medlemsliste[j].tlf = medlemi.telefon;
};
};
};
}
this.oppdaterView();
} else {
alert("Error during AJAX call. Please try again");
};
};
};
Medlemslisteobjekt.prototype.ajaxHentEndringer = function() {
// alert("ajaxhentendringer");
regelmessig.stopRegelmessig();
//heter xmlHttp men henter json
xmlHttp = HTTPObjekt();
if (xmlHttp) {
var that = medlemObjekt;
xmlHttp.open("GET", "EndringerHent?loggId=" + that.loggId, true);
xmlHttp.onreadystatechange = function(){
that.handleServerResponse(this);
};
xmlHttp.send(null);
};
};
Medlemslisteobjekt.prototype.oppdaterView = function() {
// alert("oppdaterview");
var tabellbody = document.getElementById("tbody");
while (tabellbody.rows.length >= 1) {
tabellbody.deleteRow(tabellbody.rows.length - 1);
}
if (this.medlemsliste.length > 0) {
var that = this;
for ( var i = 0; i < this.medlemsliste.length; i++) {
var rad = tabellbody.insertRow(i);
// fornavn
var textNode = document
.createTextNode(this.medlemsliste[i].fornavn);
rad.insertCell(0).appendChild(textNode);
// etternavn
var textNode = document
.createTextNode(this.medlemsliste[i].etternavn);
rad.insertCell(1).appendChild(textNode);
// adresse
var textNode = document
.createTextNode(this.medlemsliste[i].adresse);
rad.insertCell(2).appendChild(textNode);
// tlf
var textNode = document.createTextNode(this.medlemsliste[i].tlf);
rad.insertCell(3).appendChild(textNode);
// slett
var slett = document.createElement("input");
slett.type = 'button';
slett.value = 'slett';
slett.id = i;
slett.onclick = function() {
that.slettMedlem(this.id);
};
rad.insertCell(4).appendChild(slett);
// endre
var endre = document.createElement("input");
endre.type = 'button';
endre.value = 'endre';
endre.id = i;
endre.onclick = function() {
that.endreMedlem(this.id);
};
rad.insertCell(5).appendChild(endre);
};
} else {
var rad = tabellbody.insertRow(0);
// fornavn
var textNode = document.createTextNode("ingen verdier");
rad.insertCell(0).appendChild(textNode);
};
};
Medlemslisteobjekt.prototype.leggTilMedlem = function() {
// alert("leggtilmedlem");
var m = new Medlem();
m.medlemId = document.getElementById("medlemId").value;
m.fornavn = document.getElementById("fornavn").value;
m.etternavn = document.getElementById("etternavn").value;
m.adresse = document.getElementById("adresse").value;
m.tlf = document.getElementById("telefon").value;
this.ajaxLeggTilMedlem(m);
};
Medlemslisteobjekt.prototype.ajaxLeggTilMedlem = function(m) {
// alert("ajaxleggtilmedlem");
regelmessig.stopRegelmessig();
var xmlHttp = HTTPObjekt();
if (xmlHttp) {
var JSONString = JSON.stringify(m);
xmlHttp.open("POST", "MedlemDataJSON", true);
xmlHttp.setRequestHeader('Content-Type',
'application/x-www-form-urlencoded');
xmlHttp.onload = this.ajaxHentEndringer;
xmlHttp.send(JSONString);
// alert("Proever aa legge den til");
};
};
Medlemslisteobjekt.prototype.slettMedlem = function(i) {
regelmessig.stopRegelmessig();
var medlemId = this.hentId(i);
var xmlHttp = HTTPObjekt();
if (xmlHttp) {
xmlHttp.open("POST", "MedlemSlett", true);
xmlHttp.setRequestHeader('Content-Type',
'application/x-www-form-urlencoded');
xmlHttp.onload = this.ajaxHentEndringer;// this eller objekt
xmlHttp.send("medlemId=" + medlemId);
};
};
Medlemslisteobjekt.prototype.hentId = function(i) {
return this.medlemsliste[i].medlemId;
};
Medlemslisteobjekt.prototype.endreMedlem = function(id) {
var m = this.medlemsliste[id];
document.getElementById("medlemId").value = m.medlemId;
document.getElementById("fornavn").value = m.fornavn;
document.getElementById("etternavn").value = m.etternavn;
document.getElementById("adresse").value = m.adresse;
document.getElementById("telefon").value = m.tlf;
};
| JavaScript |
function OS_Scene(host,id)
{
this.$super=OS_Interface;
if (this.$super(host,id)===false) return;
delete this.$super;
this.illustration=null;
this.gradual=null;
this.filter={r:0,g:0,b:0,a:0};
var effects=
{
below:[],
above:[]
};
var paused=false;
this.isPaused=function()
{
return paused;
}
this.pause=function()
{
paused=true;
}
this.resume=function()
{
paused=false;
}
var window_resource=null;
this.getWinRes=function()
{
return window_resource;
}
var instance=this;
//活动的对话框
var activeDialog=null;
this.setActiveDialog=function(dialog)
{
activeDialog=dialog;
}
this.load=function(handler)
{
var children=this.resourceNode.childNodes;
host.status.supportingRoles=[];
for (var i=0;i<children.length;i++)
{
if (children[i].nodeType!=1) continue;
var child=children[i];
switch(child.nodeName)
{
case "world":
var worldid=child.childNodes[0].nodeValue;
this.world=OS_Resource.resource.get(worldid);
break;
case "environment":
var bgmid=child.getElementsByTagName("bgm")[0].childNodes[0].nodeValue;
this.bgm=OS_Resource.resource.get(bgmid);
break;
case "logic":
var actives=child.childNodes;
for (var j=0;j<actives.length;j++)
{
if (actives[j].nodeType!=1) continue;
if (actives[j].nodeName!="act") continue;
var active=actives[j];
if (active.getAttribute("leading"))
{
if (!host.status.leadingRole)
{
host.status.leadingRole=OS_Resource.resource.get(active.childNodes[0].nodeValue);
}
}
else
{
host.status.supportingRoles.push(OS_Resource.resource.get(active.childNodes[0].nodeValue));
}
}
break;
case "dialog":
window_resource=OS_Resource.resource.get(child.childNodes[0].nodeValue);
break;
}
}
this.loaded=true;
handler(this);
}
this.playBGM=function()
{
host.studio.playBGM([this.bgm],false);
}
//更新所有角色的位置
var updatePositions=function()
{
var upkey= {key:"up",value:0,time:host.status.checkKeyHold("up")||1};
var downkey= {key:"down",value:2,time:host.status.checkKeyHold("down")||1};
var leftkey= {key:"left",value:3,time:host.status.checkKeyHold("left")||1};
var rightkey= {key:"right",value:1,time:host.status.checkKeyHold("right")||1};
var nearest=upkey;
if (downkey.time>upkey.time) nearest=downkey;
if (leftkey.time>upkey.time) nearest=leftkey;
if (rightkey.time>upkey.time) nearest=rightkey;
//移动主角
if (nearest.time>1)
{
if (host.status.leadingRole.isInPosition())
{
host.status.leadingRole.faceto(nearest.value);
}
host.status.leadingRole.forward(null,"positionevent",function(){
var params={};
params.time=(new Date()).getTime();
//触发位置更新事件
host.status.positionTrigger.active(host.status.leadingRole,params);
});
}
else
{
if (!host.status.leadingRole.isInPosition())
{
host.status.leadingRole.forward(null,"positionevent",function(){
var params={};
params.time=(new Date()).getTime();
//触发位置更新事件
host.status.positionTrigger.active(host.status.leadingRole,params);
});
}
else if (host.status.checkKeyPressed("enter"))
{
var params={};
params.time=(new Date()).getTime();
//触发确认键事件
host.status.confirmTrigger.active(host.status.leadingRole,params);
}
}
//记录调试信息
host.debugDataR.put("Leading Role Pos-x",host.status.leadingRole.currentPosition.x.toFixed(1));
host.debugDataR.put("Leading Role Pos-y",host.status.leadingRole.currentPosition.y.toFixed(1));
//移动配角
for (var i=0;i<host.status.supportingRoles.length;i++)
{
var active_current=host.status.supportingRoles[i];
if (!active_current.isEnable()) continue;
if (active_current.wait===undefined) active_current.wait=0;
if (active_current.wait>0)
{
active_current.wait--;
}
else if (!active_current.isInPosition())
{
active_current.forward();
active_current.wait=-10;
}
else if (active_current.mode=="auto")
{
var actions=[];
if (active_current.wait==-10)
{
actions.push(4);//已经移动过了就可以等待
actions.push(5);
}
if (active_current.currentPosition.y/host.config.squareheight-1>=active_current.position.y) actions.push(0);
if (active_current.currentPosition.x/host.config.squarewidth+1<active_current.position.x+active_current.scope.colspan) actions.push(1);
if (active_current.currentPosition.y/host.config.squareheight+1<active_current.position.y+active_current.scope.rowspan) actions.push(2);
if (active_current.currentPosition.x/host.config.squarewidth-1>=active_current.position.x) actions.push(3);
var whattodo=actions[Math.floor(Math.random()*actions.length)];
if (whattodo==4 || whattodo==5)
{
active_current.wait=Math.random()*host.config.fps*0.5+host.config.fps*0.5;
}
else
{
active_current.faceto(whattodo);
active_current.forward();
}
}
host.debugDataR.put("Supporting Role "+i+" Pos-x",active_current.currentPosition.x.toFixed(1));
host.debugDataR.put("Supporting Role "+i+" Pos-y",active_current.currentPosition.y.toFixed(1));
}
}
//利用时间偏移量实现动画暂停
var calibrateEffectTime=function()
{
for (var la=0;la<2;la++)
{
if (la==0) layer="below";
if (la==1) layer="above";
for (var i=0;i<effects[layer].length;i++)
{
if (paused)
{
if (effects[layer][i].timeOffset===false)
{
effects[layer][i].timeOffset=(new Date()).getTime()-effects[layer][i].startTime;
}
else
{
effects[layer][i].startTime=(new Date()).getTime()-effects[layer][i].timeOffset;
}
}
else
{
effects[layer][i].timeOffset=false;
}
}
}
}
var update=function()
{
if (activeDialog!=null)
{
activeDialog.interceptKey();//截取按键事件
activeDialog.update();
}
else if (!!host.status.checkKeyPressed("esc"))
{
//如果退出键被按下了,启动游戏菜单
var params={};
params.position="center";
params.width=140;
params.height=150;
params.text=null;
params.key="$sceneMenuSelect_val";
params.options=[{text:"继续游戏",value:"继续"},{text:"角色状态",value:"状态"},{text:"保存游戏",value:"保存"},{text:"退出游戏",value:"退出"}];
params.callback=function()
{
var actionChoosed=host.status.V.get(params.key);
switch(actionChoosed)
{
case "状态":
var _params={};
_params.position="center";
_params.width=140;
_params.height=150;
_params.text=null;
_params.key="$sceneMenuRoleSelect_val";
_params.options=[];
var members=host.status.team.members;
for( var i=0;i<members.length;i++) if (members[i].appearance)
{
_params.options.push({text:members[i].name,value:members[i].name});
}
_params.callback=function()
{
var actionChoosed=host.status.V.get(_params.key);
switch(actionChoosed)
{
case "ESC":
activeDialog=menu001;
activeDialog.open();
break;
default:
for(var i=0;i<members.length;i++)
{
if (actionChoosed==members[i].name)
{
var params2={};
params2.position="center";
params2.width=200;
params2.height=300;
params2.text=members[i].name+" "+members[i].level+"级";
params2.key="$sceneMenuStatusSelect_val";
params2.options=[];
params2.options.push({
text:"经验值 "+members[i].experience+"/"+members[i].experienceLimit,
value:members[i].maxHp});
params2.options.push({
text:"HP值 "+members[i].hp+"/"+members[i].maxHp,
value:members[i].maxHp});
params2.options.push({
text:"Mp值 "+members[i].mp+"/"+members[i].maxMp,
value:members[i].maxMp});
params2.options.push({
text:"速度 "+(members[i].initialSpeed+members[i].speedAddition*(members[i].level-1)),
value:members[i].maxMp});
params2.options.push({
text:"攻击力 "+(members[i].initialAttack+members[i].attackAddition*(members[i].level-1)),
value:members[i].maxMp});
params2.options.push({
text:"防御力 "+(members[i].initialDefense+members[i].defenseAddition*(members[i].level-1)),
value:members[i].maxMp});
params2.options.push({
text:"魔力 "+(members[i].initialMagic+members[i].magicAddition*(members[i].level-1)),
value:members[i].maxMp});
params2.options.push({
text:"抵抗力 "+(members[i].initialResistance+members[i].resistanceAddition*(members[i].level-1)),
value:members[i].maxMp});
params2.callback=function()
{
var actionChoosed=host.status.V.get(params2.key);
switch(actionChoosed)
{
case "ESC":
activeDialog=menu002;
activeDialog.open();
break;
default:
instance.resume();
break;
}
}
var menu003=new OS_SelectDialog(host,instance,instance.getWinRes(),params2);
activeDialog=menu003;
activeDialog.open();
}
}
}
}
var menu002=new OS_SelectDialog(host,instance,instance.getWinRes(),_params);
activeDialog=menu002;
activeDialog.open();
break;
case "继续":
instance.resume();
break;
case "保存":
host.status.saveToLocal();
var paramsSave={};
paramsSave.position="center";
paramsSave.width=150;
paramsSave.height=80;
paramsSave.words=["保存成功"];
paramsSave.callback=function()
{
instance.resume();
}
activeDialog=new OS_TalkDialog(host,instance,instance.getWinRes(),paramsSave);
activeDialog.open();
break;
case "退出":
host.loopEndHooks.push(function()
{
host.changeInterface(host.config.entryInterface,"menu");
});
break;
case "ESC":
instance.resume();
break;
}
}
var menu001=new OS_SelectDialog(host,instance,instance.getWinRes(),params);
activeDialog=menu001;
instance.pause();
activeDialog.open();
} else if (!!host.status.checkKeyPressed("tab"))
{
host.status.team.nextActiveMember();
}
for (var i=0;i<host.status.supportingRoles.length;i++)
{
host.status.supportingRoles[i].update();
}
if (!paused) updatePositions();
if (!paused) host.status.frameTrigger.active();
calibrateEffectTime();
}
this.drawEffect=function(layer)
{
for (var i=0;i<effects[layer].length;i++)
{
var effectPlaying=effects[layer][i];
var time=(new Date()).getTime()-effectPlaying.startTime;
var frame=effectPlaying.effect.getFrame(time);
if (frame===false)
{
effects[layer][i]=false;
}
else
{
var left=effectPlaying.col*host.config.squarewidth-effectPlaying.effect.offset.x;
var top=effectPlaying.row*host.config.squareheight-effectPlaying.effect.offset.y;
host.stage.draw(frame,left,top);
}
}
//把播放完毕的动画从队列中去除
index=0;
while (index<effects[layer].length)
{
if (effects[layer][index]===false)
{
effects[layer].splice(index,1);
}
else
{
index++;
}
}
}
this.refresh=function()
{
update();
host.stage.clear("#000");
//屏幕跟随主角
host.stage.setViewCenter(
host.status.leadingRole.currentPosition.x+host.config.squarewidth/2,
host.status.leadingRole.currentPosition.y+host.config.squareheight/2
);
this.world.drawBelowActor();
this.drawEffect("below");
host.status.leadingRole.actor=host.status.team.getActiveMember().sceneActor;
host.status.leadingRole.drawSelf();
for (var i=0;i<host.status.supportingRoles.length;i++)
{
host.status.supportingRoles[i].drawSelf();
}
this.drawEffect("above");
this.world.drawAboveActor();
host.stage.resetViewCenter();
if (!!this.illustration)
{
host.stage.fill(OS_Resource.resource.get(this.illustration));
}
//实现渐变
if (!!this.gradual)
{
var timeTemp=(new Date()).getTime()-this.gradual.startTime;
if (timeTemp>this.gradual.duration || this.gradual.duration<=0)
{
this.filter.r=this.gradual.toR;
this.filter.g=this.gradual.toG;
this.filter.b=this.gradual.toB;
this.filter.a=this.gradual.toA;
//执行回调函数
this.gradual.callback();
this.gradual=null;
}
else
{
this.filter.r=Math.floor(this.gradual.fromR+(this.gradual.toR-this.gradual.fromR)*timeTemp/this.gradual.duration);
this.filter.g=Math.floor(this.gradual.fromG+(this.gradual.toG-this.gradual.fromG)*timeTemp/this.gradual.duration);
this.filter.b=Math.floor(this.gradual.fromB+(this.gradual.toB-this.gradual.fromB)*timeTemp/this.gradual.duration);
this.filter.a=this.gradual.fromA+(this.gradual.toA-this.gradual.fromA)*timeTemp/this.gradual.duration;
}
}
var color="rgba("+this.filter.r+","+this.filter.g+","+this.filter.b+","+this.filter.a+")";
host.stage.fill(color);
if (!!activeDialog) activeDialog.drawSelf();
}
this.playEffect=function(effect,row,col)
{
var effectPlaying={effect:effect,row:row,col:col,startTime:(new Date()).getTime(),timeOffset:false};
effects[effect.layer].push(effectPlaying);
}
this.encode=function()
{
var temp={};
temp.sceneid=this.id;
temp.activeid=host.status.leadingRole.id;
temp.positionX=host.status.leadingRole.currentPosition.x;
temp.positionY=host.status.leadingRole.currentPosition.y;
temp.distanceF=host.status.leadingRole.distanceFromLastSquare;
temp.direction=host.status.leadingRole.direction;
return JSON.stringify(temp);
}
this.decode=function(data)
{
var temp=eval("("+data+")");
host.status.leadingRole=OS_Resource.resource.get(temp.activeid);
host.status.leadingRole.deoccupy();
host.status.leadingRole.currentPosition.x=temp.positionX;
host.status.leadingRole.currentPosition.y=temp.positionY;
host.status.leadingRole.distanceFromLastSquare=temp.distanceF;
host.status.leadingRole.direction=temp.direction;
host.status.leadingRole.occupy();
}
}
OS_Resource.Builder.put("scene",OS_Scene);
| JavaScript |
//条件集合
function OS_Condition_Group(host,active,node)
{
this.$super=OS_Condition;
this.$super(host,active,node);
delete this.$super;
var conditionList=[];
var type="and";
if (!!node.getAttribute("type")) type=node.getAttribute("type");
for (var i=0;i<node.childNodes.length;i++)
{
if (node.childNodes[i].nodeType!=1)
{
continue;
}
var conditionNode=node.childNodes[i];
var condition=OS_Condition.getInstance(host,active,conditionNode);
if (!!condition) conditionList.push(condition);
}
this.check=function()
{
var res=true;
for (var i=0;i<conditionList.length;i++)
{
switch(type)
{
case "and":res=res&&conditionList[i].check();break;
case "or":res=res||conditionList[i].check();break;
case "xor":res=res^conditionList[i].check();break;
}
}
return res;
}
}
OS_Condition.list.put("conditionGroup",OS_Condition_Group);
//等于
function OS_Condition_EQ(host,active,node)
{
this.$super=OS_Condition;
this.$super(host,active,node);
delete this.$super;
var key=node.getAttribute("key");
var value=node.getAttribute("value");
this.check=function()
{
var thev=host.status.V.get(key);
if (thev==null) thev="null";
if (thev==value) return true;
else return false;
}
}
OS_Condition.list.put("eqCondition",OS_Condition_EQ);
//不等于
function OS_Condition_NEQ(host,active,node)
{
this.$super=OS_Condition;
this.$super(host,active,node);
delete this.$super;
var key=node.getAttribute("key");
var value=node.getAttribute("value");
this.check=function()
{
var thev=host.status.V.get(key);
if (thev!=value) return true;
else return false;
}
}
OS_Condition.list.put("neqCondition",OS_Condition_NEQ);
//大于
function OS_Condition_GT(host,active,node)
{
this.$super=OS_Condition;
this.$super(host,active,node);
delete this.$super;
var key=node.getAttribute("key");
var value=node.getAttribute("value");
this.check=function()
{
var thev=host.status.V.get(key);
if (thev>value) return true;
else return false;
}
}
OS_Condition.list.put("gtCondition",OS_Condition_GT);
//大于等于
function OS_Condition_EGT(host,active,node)
{
this.$super=OS_Condition;
this.$super(host,active,node);
delete this.$super;
var key=node.getAttribute("key");
var value=node.getAttribute("value");
this.check=function()
{
var thev=host.status.V.get(key);
if (thev>=value) return true;
else return false;
}
}
OS_Condition.list.put("egtCondition",OS_Condition_EGT);
//小于
function OS_Condition_LT(host,active,node)
{
this.$super=OS_Condition;
this.$super(host,active,node);
delete this.$super;
var key=node.getAttribute("key");
var value=node.getAttribute("value");
this.check=function()
{
var thev=host.status.V.get(key);
if (thev<value) return true;
else return false;
}
}
OS_Condition.list.put("ltCondition",OS_Condition_LT);
//小于等于
function OS_Condition_ELT(host,active,node)
{
this.$super=OS_Condition;
this.$super(host,active,node);
delete this.$super;
var key=node.getAttribute("key");
var value=node.getAttribute("value");
this.check=function()
{
var thev=host.status.V.get(key);
if (thev<=value) return true;
else return false;
}
}
OS_Condition.list.put("eltCondition",OS_Condition_ELT);
| JavaScript |
function OS_Window(host,id)
{
this.$super=OS_Resource;
if (this.$super(host,id)===false) return;
delete this.$super;
var source=null;
this.load=function(handler)
{
source=OS_Resource.resource.get(this.resourceNode.getElementsByTagName("source")[0].childNodes[0].nodeValue);
this.loaded=true;
handler();
}
this.drawSelf=function(context,left,top,width,height,flag)
{
if (height<16) return;
var image=source.getImage();
//画背景
context.drawImage(image,0,0,64,64,left+4,top+4,width-8,height-8);
//画四角
context.drawImage(image,64,0,8,8,left,top,8,8);
context.drawImage(image,120,0,8,8,left+width-8,top,8,8);
context.drawImage(image,64,56,8,8,left,top+height-8,8,8);
context.drawImage(image,120,56,8,8,left+width-8,top+height-8,8,8);
//画边
context.drawImage(image,72,0,8,8,left+8,top,width-16,8);
context.drawImage(image,64,8,8,8,left,top+8,8,height-16);
context.drawImage(image,72,56,8,8,left+8,top+height-8,width-16,8);
context.drawImage(image,120,48,8,8,left+width-8,top+8,8,height-16);
//画确认键
if (flag>0)
{
var sleft=0;
var stop=0;
var tleft=left+width-32;
var ttop=top+height-20;
if (flag==1||flag==8){sleft=96;stop=64;}
if (flag==2||flag==7){sleft=112;stop=64;}
if (flag==3||flag==6){sleft=112;stop=80;}
if (flag==4||flag==5){sleft=96;stop=80;}
context.drawImage(image,sleft,stop,16,16,tleft,ttop,16,16);
}
}
}
OS_Resource.Builder.put("window",OS_Window); | JavaScript |
function OS_Variable()
{
var data = null;
this.variableTrigger = Array();
this.set = function(o)
{
this.variableTrigger.forEach(function(it){
if (it.check(o))
{
it.action();
}
});
data=o;
}
this.get = function()
{
return data;
}
}
| JavaScript |
function OS_Sprite(host,id)
{
this.$super=OS_Resource;
if (this.$super(host,id)===false) return;
delete this.$super;
}
| JavaScript |
function OS_Menu(host,id)
{
this.$super = OS_Interface;
if (this.$super(host,id)===false) return;
delete this.$super;
var selectList=[];
var pointer=0;
host.status.reset();
var bgm=null;
var backgroundImage="#fff";
var imageList=[];
this.load=function(handler)
{
for (var i=0;i<this.resourceNode.childNodes.length;i++)
{
switch(this.resourceNode.childNodes[i].nodeName)
{
case "background":
var sourceid=this.resourceNode.childNodes[i].textContent;
backgroundImage=OS_Resource.resource.get(sourceid);
break;
case "environment":
var typeIndex=0;
for (var j=0;j<this.resourceNode.childNodes[i].attributes.length;j++)
{
if (this.resourceNode.childNodes[i].attributes[j].nodeName=="type") typeIndex=j;
}
var playType=this.resourceNode.childNodes[i].attributes[typeIndex].nodeValue;
var bgmid=null;
for (var j=0;j<this.resourceNode.childNodes[i].childNodes.length;j++)
{
if (this.resourceNode.childNodes[i].childNodes[j].nodeName=="bgm") bgmid=this.resourceNode.childNodes[i].childNodes[j].childNodes[0].nodeValue;
}
bgm=OS_Resource.resource.get(bgmid);
break;
}
}
for (var i=0;i<this.resourceNode.childNodes.length;i++)
{
switch(this.resourceNode.childNodes[i].nodeName)
{
case "imageList":
var images=this.resourceNode.childNodes[i].childNodes;
for (var j=0;j<images.length;j++)
if (images[j].nodeType==1 && images[j].nodeName=="imageArea")
{
var imageTemp={};
var image=images[j];
var source=image.getElementsByTagName("source")[0].childNodes[0].nodeValue;
imageTemp.imageres=OS_Resource.resource.get(source);
var position=image.getElementsByTagName("position")[0];
imageTemp.position={
x:position.getElementsByTagName("x")[0].childNodes[0].nodeValue,
y:position.getElementsByTagName("y")[0].childNodes[0].nodeValue,
};
imageList.push(imageTemp);
}
break;
}
}
for (var i=0;i<this.resourceNode.childNodes.length;i++)
{
switch(this.resourceNode.childNodes[i].nodeName)
{
case "selectList":
var selects=this.resourceNode.childNodes[i].childNodes;
for (var j=0;j<selects.length;j++)
if (selects[j].nodeType==1 && selects[j].nodeName=="select")
{
var selectTemp={};
var select=selects[j];
var index=select.getAttribute("index");
var text=select.getElementsByTagName("text")[0];
var position=select.getElementsByTagName("position")[0];
selectTemp.text={
content:text.childNodes[0].nodeValue,
size:text.getAttribute("size"),
align:text.getAttribute("align"),
shadow:text.getAttribute("shadow"),
color:text.getAttribute("color"),
bold:text.getAttribute("bold")
};
selectTemp.position={
x:position.getElementsByTagName("x")[0].childNodes[0].nodeValue,
y:position.getElementsByTagName("y")[0].childNodes[0].nodeValue,
};
selectTemp.act=function(){};
if (select.getElementsByTagName("goto").length>0)
{
var interfaceid=select.getElementsByTagName("goto")[0].childNodes[0].nodeValue;
var interfacetype="scene";
if (select.getElementsByTagName("goto")[0].hasAttribute("type"))
{
interfacetype=select.getElementsByTagName("goto")[0].getAttribute("type");
}
var changemusic=true;
if (select.getElementsByTagName("goto")[0].hasAttribute("cbgm"))
{
changemusic=eval(select.getElementsByTagName("goto")[0].getAttribute("cbgm"));
}
(function(id,type,cbgm){
selectTemp.act=function(){
host.changeInterface(id,type,cbgm);
};
})(interfaceid,interfacetype,changemusic);
}
selectList[index]=selectTemp;
}
break;
}
}
this.loaded=true;
handler(this);
}
var pointerUp=function()
{
pointer--;
if (pointer<0)
{
pointer=selectList.length-1;
}
}
var pointerDown=function()
{
pointer++;
if (pointer>=selectList.length)
{
pointer=0;
}
}
var update=function()
{
var upkey=host.status.checkKeyPressed("up");
var downkey=host.status.checkKeyPressed("down");
var enterkey=host.status.checkKeyPressed("enter");
if (enterkey)
{
selectList[pointer].act();
}
else if (upkey)
{
pointerUp();
}
else if (downkey)
{
pointerDown();
}
}
this.refresh=function()
{
host.stage.clear(backgroundImage);
update();
for (var i=0;i<imageList.length;i++)
{
var image=imageList[i];
var left=OS_Common.eval(image.position.x);
var top=OS_Common.eval(image.position.y);
host.stage.getContext().drawImage(image.imageres.getImage(),left,top);
}
for (var i=0;i<selectList.length;i++)
{
var select=selectList[i];
var text={};
text.content=select.text.content;
text.size=select.text.size;
text.align=select.text.align;
text.color="#000";
if (!!select.text.color){text.color=select.text.color;};
if (select.text.bold=="true"){text.bold=true;}
if (select.text.shadow=="true")
{
text.shadow={};
text.shadow.offsetX=0;
text.shadow.offsetY=0;
text.shadow.blur=10;
text.shadow.color="#000";
}
if (pointer==i)
{
var duration=1000;
var nowTime=(new Date()).getTime();
var alpha=Math.sin(Math.PI*(nowTime%duration/duration))*0.2+0.2;
text.background="rgba(255,255,255,"+alpha+")";
}
var left=OS_Common.eval(select.position.x);
var top=OS_Common.eval(select.position.y);
host.stage.write(text,left,top);
}
}
this.playBGM=function()
{
if (!!bgm)
{
host.studio.playBGM([bgm],false);
}
}
}
OS_Resource.Builder.put("menu",OS_Menu); | JavaScript |
function OS_BattleEffect(host,id)
{
this.$super=OS_Effect;
if (this.$super(host,id)===false) return;
delete this.$super;
this.load=function(handler)
{
this.loadTimestamps();
this.offset={
x:Number(this.resourceNode.getElementsByTagName("offset")[0].getElementsByTagName("x")[0].childNodes[0].nodeValue),
y:Number(this.resourceNode.getElementsByTagName("offset")[0].getElementsByTagName("y")[0].childNodes[0].nodeValue),
}
this.loaded=true;
handler(this);
}
}
OS_Resource.Builder.put("battleEffect",OS_BattleEffect);
| JavaScript |
function OS_Covering(host,id)
{
this.$super=OS_Bitmap;
if (this.$super(host,id)===false) return;
delete this.$super;
this.integrate=false;
this.passable=true;
this.load=function(handler)
{
this.loadBitmap();
if (this.resourceNode.getElementsByTagName("integrate").length>0)
{
this.integrate=true;
}
if (this.resourceNode.getElementsByTagName("forbidden").length>0)
{
this.passable=false;
}
this.loaded=true;
handler(this);
}
}
OS_Resource.Builder.put("covering",OS_Covering); | JavaScript |
/**
* @fileOverview Castle游戏实例的debug单元类源文件
* @author <a href="http://sivory.my.phpcloud.com">Sivory</a>
* @version 0.0.1
*/
(function() {
/** @exports _Class as Name.Sivory.Castle.Core.Debug */
var _Class =
/**
* @class Castle游戏实例的debug单元类。它主要负责记录调试信息。
* @param {Name.Sivory.Castle.Core.Game} game 一个游戏实例,参见{@link Name.Sivory.Castle.Core.Game}
* @author <a href="http://sivory.my.phpcloud.com">Sivory</a>
* @version 0.0.1
*/
Name.Sivory.Castle.Core.Debug = function(game) {
/**
* @private
* @field
* @type Name.Sivory.Castle.Core.Game
* @description 调试单元所在的游戏实例
* @since 0.0.1
*/
this.game = game;
/**
* @private
* @field
* @type Name.Sivory.Castle.Util.HashTable
* @description 游戏调试信息,将显示在界面左上角
* @since 0.0.1
*/
this.debugDataL = new Name.Sivory.Castle.Util.HashTable();
/**
* @private
* @field
* @type Name.Sivory.Castle.Util.HashTable
* @description 游戏调试信息,将显示在界面右上角
* @since 0.0.1
*/
this.debugDataR = new Name.Sivory.Castle.Util.HashTable();
/**
* @private
* @field
* @type Number
* @description 用于记录循环体开始的时间
* @since 0.0.1
*/
this.frameStartTime = 0;
/**
* @private
* @field
* @type Number
* @description 用于记录循环体结束的时间
* @since 0.0.1
*/
this.frameEndTime = 0;
/**
* @private
* @field
* @type Number
* @description 用于记录循环体开始的时间
* @since 0.0.1
*/
this.framesPerSecond = 0;
/**
* @private
* @field
* @type Number
* @description 上一个被记录的帧的时间,用于计算FPS
* @since 0.0.1
*/
this.lastRecordFrameTime = 0;
/**
* @private
* @field
* @type Number
* @description 上一个被记录时帧的计数,用于计算FPS
* @since 0.0.1
*/
this.lastRecordFrameCount = 0;
};
/**
* @public
* @function
* @description 添加调试信息
* @param {String} key 调试信息的标识,将显示成 <strong> key : val </strong> 的形式
* @param {String} val 调试信息的内容,将显示成 <strong> key : val </strong> 的形式
* @param {String} pos 调试信息显示的位置,<strong> "left" </strong> 为显示在左上角,<strong> "right" </strong>为显示在右上角
* @since 0.0.1
*/
_Class.prototype.addInfo = function(key, val, pos) {
if(pos === null || pos === undefined) pos = "left";
var debugData = null;
if(pos === "left") debugData = this.debugDataL;
if(pos === "right") debugData = this.debugDataR;
debugData.put(key, val);
}
/**
* @public
* @function
* @description 在一个循环体中开启调试
* @since 0.0.1
*/
_Class.prototype.start = function() {
//初始化调试信息
this.debugDataL.clear();
this.debugDataR.clear();
//在调试信息中加入内核版本号
this.debugDataL.put("Engine Version", this.game.V);
//在调试信息中加入浏览器信息
var agents = {
"C": "Chrome",
"F": "FireFox",
"O": "Opera",
"S": "Safari",
"I": "Internet Explorer"
};
this.debugDataL.put("User Agent", agents[this.game.userAgent]);
//记录帧开始的时间
this.frameStartTime = (new Date()).getTime();
//计算帧率
var howlong = this.frameStartTime - this.lastRecordFrameTime;
var howmany = this.game.frameCount - this.lastRecordFrameCount;
if(howlong > 200) {
this.framePerSecond = (howmany / howlong * 1000).toFixed(1);
this.lastRecordFrameTime = this.frameStartTime;
this.lastRecordFrameCount = this.game.frameCount;
}
this.debugDataL.put("FPS", this.framePerSecond);
}
/**
* @public
* @function
* @description 在一个循环体中结束调试
* @since 0.0.1
*/
_Class.prototype.finish = function() {
//计算单帧的渲染时间
this.frameEndTime = new Date();
var runtime = this.frameEndTime - this.frameStartTime;
this.debugDataL.put("Frame Rendering Time", runtime + " ms");
//如果开启调试模式的话,则显示调试信息
if( !! this.game.stage && this.game.config.debug === true) {
for(var pos in {
"L": null,
"R": null
}) {
var dubugData = this["debugData" + pos];
var keys = debugData.keySet();
if( !! keys.length) for(var i = 0; i < keys.length; i++) {
this.game.stage.write({
content: keys[i] + ": " + debugData.get(keys[i]),
size: 10,
color: "#000"
}, 10, 10 + i * 20);
}
}
}
}
})(); | JavaScript |
function OS_SelectDialog(game,scene,winres,params)
{
this.$super=OS_Dialog;
this.$super(game,scene,winres,params);
delete this.$super;
var text=params.text;
var lines=null;
var linePointer=0;
var duration=1000;
var lineOffset=0;
if (!!text) lineOffset=1;
var lineS=0;
var lineE=Math.floor((this.getHeight()-this.getPaddingT()*2-lineOffset*this.getLineHeight())/this.getLineHeight())-1;
var instance=this;
this.updateContent=function()
{
var nowTime=(new Date()).getTime();
var alpha=Math.sin(Math.PI*(nowTime%duration/duration))*0.2+0.2;
var background="rgba(255,255,255,"+alpha+")";
if (text!=null)
{
var drawing={
type:"text",
line:0,
text:text,
textLen:text.length,
background:null
};
this.drawList.push(drawing);
}
if (this.getActiveKey()=="down")
{
linePointer=(linePointer+1)%params.options.length;
}
if (this.getActiveKey()=="up")
{
linePointer=(linePointer-1+params.options.length)%params.options.length;
}
if (this.getActiveKey()=="esc")
{
game.status.V.put(params.key,"ESC");
this.close();
}
if (linePointer<lineS) {lineS=linePointer;lineE=lineS+1;}
if (linePointer>lineE) {lineE=linePointer;lineS=lineE-1;}
for (var i=lineS;i<=lineE&&!!params.options[i];i++)
{
var drawing={
type:"text",
line:i-lineS+lineOffset,
text:params.options[i].text,
textLen:params.options[i].text.length,
background:linePointer==i?background:null,
disable:params.options[i].disable
};
this.drawList.push(drawing);
}
if (this.getActiveKey()=="enter" || this.getActiveKey()=="space")
{
if (linePointer<params.options.length && !params.options[linePointer].disable)
{
game.status.V.put(params.key,params.options[linePointer].value);
this.close();
}
}
}
}
| JavaScript |
function OS_Bitmap(host,id)
{
this.$super=OS_Resource;
if (this.$super(host,id)===false) return;
delete this.$super;
this.width=0;
this.height=0;
this.offsetx=0;
this.offsety=0;
this.source=null;
this.loadBitmap=function()
{
var imageid=this.resourceNode.getElementsByTagName("source")[0].childNodes[0].nodeValue;
this.source=OS_Resource.resource.get(imageid);
if (this.resourceNode.getElementsByTagName("size").length>0)
{
this.width=Number(this.resourceNode.getElementsByTagName("size")[0].getElementsByTagName("width")[0].childNodes[0].nodeValue);
this.height=Number(this.resourceNode.getElementsByTagName("size")[0].getElementsByTagName("height")[0].childNodes[0].nodeValue);
}
else
{
this.width=host.config.squarewidth;
this.height=host.config.squareheight;
}
if (this.resourceNode.getElementsByTagName("position").length>0)
{
this.offsetx=Number(this.resourceNode.getElementsByTagName("position")[0].getElementsByTagName("left")[0].childNodes[0].nodeValue);
this.offsety=Number(this.resourceNode.getElementsByTagName("position")[0].getElementsByTagName("top")[0].childNodes[0].nodeValue);
}
else
{
this.offsetx=Number(this.resourceNode.getElementsByTagName("coordinate")[0].getElementsByTagName("col")[0].childNodes[0].nodeValue)*this.width;
this.offsety=Number(this.resourceNode.getElementsByTagName("coordinate")[0].getElementsByTagName("row")[0].childNodes[0].nodeValue)*this.height;
}
if (this.resourceNode.getElementsByTagName("span").length>0)
{
this.width*=Number(this.resourceNode.getElementsByTagName("span")[0].getElementsByTagName("colspan")[0].childNodes[0].nodeValue);
this.height*=Number(this.resourceNode.getElementsByTagName("span")[0].getElementsByTagName("rowspan")[0].childNodes[0].nodeValue);
}
}
}
| JavaScript |
/**
* @fileOverview 游戏手柄类源文件
* @author <a href="http://sivory.my.phpcloud.com">Sivory</a>
* @version 0.0.0
*/
(function() {
/** @exports _Class as Name.Sivory.Castle.Core.Controller */
var _Class =
/**
* @class 游戏手柄类,将负责监听窗口键盘事件并触发游戏中的操作事件。
* @param {Name.Sivory.Castle.Core.Game} game 游戏实例对象,参见{@link Name.Sivory.Castle.Core.Game}
* @author <a href="http://sivory.my.phpcloud.com">Sivory</a>
* @version 0.0.1
*/
Name.Sivory.Castle.Core.Controller = function(g) {
/**
* @private
* @field
* @type Name.Sivory.Castle.Core.Game
* @description 游戏实例引用
* @since 0.0.1
*/
this.game = g;
/**
* @private
* @field
* @type Name.Sivory.Castle.Util.HashTable
* @description 游戏运行时的键盘状态
* @since 0.0.1
*/
this.keyboardStatus = new Name.Sivory.Castle.Util.HashTable();
/**
* @private
* @field
* @type Name.Sivory.Castle.Core.Resource.KeyConfig
* @description 游戏按键配置对象
* @since 0.0.1
*/
this.keyconf = null;
//初始化
this.init();
};
/**
* @private
* @function
* @description 初始化游戏事件处理
* @since 0.0.1
*/
_Class.prototype.init = function() {
var _ins = this;
var onKeydown = function(e) {
if(!_ins.keyconf) return;
var key = _ins.keyconf.keycode(e.keyCode);
if(key == "unknow") return;
e.preventDefault();
var d = new Date();
if(!game.status.getKeyboardStatus(key)) {
game.status.setKeyboardStatus(key, d.getTime());
};
};
var onKeyup = function(e) {
if(!keyconf) return;
var key = keyconf.keycode(e.keyCode);
if(key == "unknow") return;
e.preventDefault();
game.status.setKeyboardStatus(key, false);
};
var onBlur = function(e) {
e.preventDefault();
console.log("blur");
game.status.resetKeyboardStatus();
};
window.addEventListener("keydown", onKeydown, false);
window.addEventListener("keyup", onKeyup, false);
window.addEventListener("blur", onKeyup, false);
};
/**
* @public
* @function
* @description 设置游戏按键信息
* @param {Name.Sivory.Castle.Core.Resource.KeyConfig} keys 游戏键位配置对象。
* @since 0.0.1
*/
_Class.prototype.setKeys = function(keys) {
this.keyconf = k;
};
/**
* @private
* @function
* @description 游戏事件托管
* @param {String} key 设置key键已被按下
* @since 0.0.1
*/
_Class.prototype.getKeyboardStatus = function(key) {
if(keyboardStatus.containsKey(key)) {
return keyboardStatus.get(key);
} else {
return false;
}
};
})(); | JavaScript |
function OS_Terrain(host,id)
{
this.$super=OS_Bitmap;
if (this.$super(host,id)===false) return;
delete this.$super;
this.integrate=false;
this.passable=true;
this.load=function(handler)
{
this.loadBitmap();
if (this.resourceNode.getElementsByTagName("integrate").length>0)
{
this.integrate=true;
}
if (this.resourceNode.getElementsByTagName("forbidden").length>0)
{
this.passable=false;
}
this.loaded=true;
handler(this);
}
}
OS_Resource.Builder.put("terrain",OS_Terrain);
| JavaScript |
function OS_Ornament(host,id)
{
this.$super=OS_Bitmap;
if (this.$super(host,id)===false) return;
delete this.$super;
this.cover=false;
this.passable=true;
this.load=function(handler)
{
this.loadBitmap();
if (this.resourceNode.getElementsByTagName("cover").length>0)
{
this.cover=true;
}
if (this.resourceNode.getElementsByTagName("forbidden").length>0)
{
this.passable=false;
}
this.loaded=true;
handler(this);
}
}
OS_Resource.Builder.put("ornament",OS_Ornament); | JavaScript |
/**
* @fileOverview 散列表类源文件
* @author <a href="http://sivory.my.phpcloud.com">Sivory</a>
* @version 0.0.1
*/
(function() {
/** @exports _Class as Name.Sivory.Castle.Util.HashTable */
var _Class =
/**
* @class 散别表类
* @author <a href="http://sivory.my.phpcloud.com">Sivory</a>
* @version 0.0.1
*/
Name.Sivory.Castle.Util.HashTable = function() {
/**
* @private
* @field
* @type Object
* @description 用于记录散列表信息
* @since 0.0.1
*/
this._hash = {};
/**
* @private
* @field
* @type Number
* @description 散列表中信息的条数
* @since 0.0.1
*/
this._count = 0;
};
/**
* @public
* @function
* @description 向散列表中添加数据
* @param {String} key 待添加的数据的索引
* @param {Object} value 待添加的数据
* @returns {Boolean} 是否成功添加数据
* @since 0.0.1
*/
_Class.prototype.put = function(key, value) {
if(this._hash.hasOwnProperty(key)) {
this._hash[key] = value;
return true;
} else {
this._hash[key] = value;
this._count++;
return true;
}
}
/**
* @public
* @function
* @description 从散列表中取出数据
* @param {String} key 需要取出的数据的索引
* @returns {Object} 取出的数据
* @since 0.0.1
*/
_Class.prototype.get = function(key) {
if(this.containsKey(key)) return this._hash[key];
}
/**
* @public
* @function
* @description 获得散列表中数据的数目
* @returns {Number} 散列表中数据的数目
* @since 0.0.1
*/
_Class.prototype.size = function() {
return this._count;
}
/**
* @public
* @function
* @description 检查散列表是否为空
* @returns {Boolean} 检查结果
* @since 0.0.1
*/
_Class.prototype.isEmpty = function() {
if(this._count <= 0) return true;
else return false;
}
/**
* @public
* @function
* @description 检查散列表是否包含某一个索引
* @param {String} key 需要检测的索引
* @returns {Boolean} 检查结果
* @since 0.0.1
*/
_Class.prototype.containsKey = function(key) {
return this._hash.hasOwnProperty(key);
}
/**
* @public
* @function
* @description 检查散列表是否包含某一个值
* @param {String} value 需要检测的值
* @returns {Boolean} 检查结果
* @since 0.0.1
*/
_Class.prototype.containsValue = function(value) {
for(var strKey in this._hash) {
if(this._hash[strKey] === value) return true;
}
return false;
}
/**
* @public
* @function
* @description 删除散列表中的某个索引
* @param {String} key 待删除数据的索引
* @since 0.0.1
*/
_Class.prototype.remove = function(key) {
delete this._hash[key];
this._count--;
}
/**
* @public
* @function
* @description 清空整个散列表
* @since 0.0.1
*/
_Class.prototype.clear = function() {
this._hash = {};
this._count = 0;
}
/**
* @public
* @function
* @description 取得整个散列表的索引的集合,若散列表中没有元素则返回null
* @returns {Array 索引的集合
* @since 0.0.1
*/
_Class.prototype.keySet = function() {
var arrKeySet = new Array();
var index = 0;
for(var strKey in this._hash) {
arrKeySet[index++] = strKey;
}
return(arrKeySet.length == 0) ? null : arrKeySet;
}
/**
* @public
* @function
* @description 取得整个散列表的值的集合,若散列表中没有元素则返回null
* @returns {Array} 值的集合
* @since 0.0.1
*/
_Class.prototype.values = function() {
var arrValues = new Array();
var index = 0;
for(var strKey in this._hash) {
arrValues[index++] = this._hash[strKey];
}
return(arrValues.length == 0) ? null : arrValues;
}
/**
* @public
* @function
* @description 对当前散列表进行JSON编码
* @returns {String} 编码后的JSON字符串
* @since 0.0.1
*/
_Class.prototype.encode = function() {
return JSON.stringify(hash);
}
/**
* @public
* @static
* @function
* @description 对所给的JSON字符串进行解码
* @returns {Name.Sivory.Castle.Util.HashTable} 解码后的散列表对象
* @since 0.0.1
*/
_Class.decode = function(jsonStr) {
var hashTemp = new Name.Sivory.Castle.Util.HashTable();
try {
hashTemp._hash = eval("(" + jsonStr + ")");
return hashTemp;
} catch(err) {
console.log("实例化哈希表失败");
}
}
})(); | JavaScript |
function OS_Map(host,id)
{
this.$super=OS_Resource;
if (this.$super(host,id)===false) return;
delete this.$super;
this.rowCount=0;
this.colCount=0;
this.mapdata=[];
this.load=function(handler)
{
this.rowCount=Number(this.resourceNode.getElementsByTagName("size")[0].getElementsByTagName("rowCount")[0].childNodes[0].nodeValue);
this.colCount=Number(this.resourceNode.getElementsByTagName("size")[0].getElementsByTagName("colCount")[0].childNodes[0].nodeValue);
var defaultTid=this.resourceNode.getElementsByTagName("defaultT")[0].childNodes[0].nodeValue;
var defaultT=OS_Resource.resource.get(defaultTid);
for (var i=0;i<this.rowCount;i++)
{
var row=[];
for (var j=0;j<this.colCount;j++)
{
var square={};
square.terrain=defaultT;
square.occupied=false;
row.push(square);
}
this.mapdata.push(row);
}
var rows=this.resourceNode.getElementsByTagName("row");
for (var i=0;i<rows.length;i++)
{
var row=rows[i];
var row_index=Number(row.getAttribute("index"));
var cols=row.getElementsByTagName("col");
for (var j=0;j<cols.length;j++)
{
var col=cols[j];
var col_index=Number(col.getAttribute("index"));
var square=this.mapdata[row_index][col_index];
if (col.getElementsByTagName("t").length>0)
{
var terrainId=col.getElementsByTagName("t")[0].childNodes[0].nodeValue;
square.terrain=OS_Resource.resource.get(terrainId);
}
if (col.getElementsByTagName("c").length>0)
{
var coveringId=col.getElementsByTagName("c")[0].childNodes[0].nodeValue;
square.covering=OS_Resource.resource.get(coveringId);
}
if (col.getElementsByTagName("o").length>0)
{
var ornamentId=col.getElementsByTagName("o")[0].childNodes[0].nodeValue;
square.ornament=OS_Resource.resource.get(ornamentId);
}
}
}
this.loaded=true;
handler(this);
}
this.drawBelowCache=function()
{
this.belowCacheCanvas=document.createElement("canvas");
this.belowCacheCanvas.width=this.colCount*host.config.squarewidth;
this.belowCacheCanvas.height=this.rowCount*host.config.squareheight;
this.belowCacheContext=this.belowCacheCanvas.getContext("2d");
for (var i=0;i<this.rowCount;i++)
{
for (var j=0;j<this.colCount;j++)
{
var offsetx=j*host.config.squarewidth;
var offsety=i*host.config.squareheight;
if (!this.mapdata[i][j].terrain.integrate)
{
host.stage.draw(this.mapdata[i][j].terrain,offsetx,offsety,this.belowCacheContext);
}
else
{
host.stage.fix(this,"terrain",i,j,this.belowCacheContext);
}
if (!!this.mapdata[i][j].covering)
{
if (!this.mapdata[i][j].covering.integrate)
{
host.stage.draw(this.mapdata[i][j].covering,offsetx,offsety,this.belowCacheContext);
}
else
{
host.stage.fix(this,"covering",i,j,this.belowCacheContext);
}
}
if (!!this.mapdata[i][j].ornament && !this.mapdata[i][j].ornament.cover)
{
host.stage.draw(this.mapdata[i][j].ornament,offsetx,offsety,this.belowCacheContext);
}
}
}
}
this.drawBelowActor=function()
{
if (!this.belowCacheCanvas) this.drawBelowCache();
host.stage.getContext().drawImage(this.belowCacheCanvas,0,0);
for (var i=0;i<this.rowCount;i++)
{
for (var j=0;j<this.colCount;j++)
{
var offsetx=j*host.config.squarewidth;
var offsety=i*host.config.squareheight;
if (host.config.debug && this.mapdata[i][j].occupied)
{
host.stage.drawSquare("rgba(0,0,255,0.2)",offsetx,offsety);
}
}
}
}
this.drawAboveCache=function()
{
this.aboveCacheCanvas=document.createElement("canvas");
this.aboveCacheCanvas.width=this.colCount*host.config.squarewidth;
this.aboveCacheCanvas.height=this.rowCount*host.config.squareheight;
this.aboveCacheContext=this.aboveCacheCanvas.getContext("2d");
for (var i=0;i<this.rowCount;i++)
{
for (var j=0;j<this.colCount;j++)
{
var offsetx=j*host.config.squarewidth;
var offsety=i*host.config.squareheight;
if (!!this.mapdata[i][j].ornament && this.mapdata[i][j].ornament.cover)
{
host.stage.draw(this.mapdata[i][j].ornament,offsetx,offsety);
}
}
}
}
this.drawAboveActor=function()
{
for (var i=0;i<this.rowCount;i++)
{
for (var j=0;j<this.colCount;j++)
{
var offsetx=j*host.config.squarewidth;
var offsety=i*host.config.squareheight;
if (!!this.mapdata[i][j].ornament && this.mapdata[i][j].ornament.cover)
{
host.stage.draw(this.mapdata[i][j].ornament,offsetx,offsety);
}
}
}
}
this.checkPass=function(row,col,coverable)
{
var square=this.mapdata[row][col];
var pass=square.terrain.passable;
if (!!square.covering)
{
pass=pass&&square.covering.passable;
}
if (!!square.ornament)
{
pass=pass&&square.ornament.passable;
}
if (!coverable)
{
pass=pass&&!square.occupied;
}
return pass;
}
//通行检测
this.checkActivePosition=function(active)
{
var position_x=Math.round(active.currentPosition.x);
var position_y=Math.round(active.currentPosition.y);
if (position_x<0||position_x>(this.colCount-1)*host.config.squarewidth) return false;
if (position_y<0||position_y>(this.rowCount-1)*host.config.squareheight) return false;
var row1=Math.floor(position_y / host.config.squarewidth);
var row2=Math.ceil(position_y / host.config.squarewidth);
var col1=Math.floor(position_x / host.config.squareheight);
var col2=Math.ceil(position_x / host.config.squareheight);
if (!this.checkPass(row1,col1,active.coverable)) return false;
if (!this.checkPass(row1,col2,active.coverable)) return false;
if (!this.checkPass(row2,col1,active.coverable)) return false;
if (!this.checkPass(row2,col2,active.coverable)) return false;
return true;
}
}
OS_Resource.Builder.put("map",OS_Map); | JavaScript |
function OS_BattleActor(host,id)
{
this.$super=OS_Actor;
if (this.$super(host,id)===false) return;
delete this.$super;
this.load=function(handler)
{
this.loadActions();
this.loaded=true;
handler(this);
}
}
OS_Resource.Builder.put("battleActor",OS_BattleActor); | JavaScript |
function OS_Actor(host, id) {
this.$super = OS_Sprite;
if(this.$super(host, id) === false) return;
delete this.$super;
this.actions = {};
this.loadActions = function() {
var actionlist = this.resourceNode.getElementsByTagName("actions")[0].getElementsByTagName("action");
for(var i = 0; i < actionlist.length; i++) {
var action = actionlist[i];
var index = action.getAttribute("index");
var frameid = action.childNodes[0].nodeValue;
this.actions[index] = OS_Resource.resource.get(frameid);
}
};
} | JavaScript |
var OS_Common={
is : function(obj, type) {
return (type === "Null" && obj === null) || (type === "Undefined" && obj === void 0) || (type === "Number" && isFinite(obj)) || Object.prototype.toString.call(obj).slice(8, -1) === type
}
,
eval : function(str)
{
if (!window.$starttime) window.$starttime=(new Date()).getTime();
window.$time=(new Date()).getTime()-window.$starttime;
try{
var value=eval("("+str+")");
}
catch(err)
{
var value=null;
}
return value;
}
}
| JavaScript |
function OS_TalkDialog(game,scene,winres,params)
{
this.$super=OS_Dialog;
this.$super(game,scene,winres,params);
delete this.$super;
var charDelay=50;
var textTime=null;
var lines=null;
var wordPointer=0;
var linePointer=0;
var waitConfirm=false;
var instance=this;
var initLines=function()
{
lines=[];
var text=params.words[wordPointer];
var start=0;
var stop=1;
while (stop<=text.length)
{
var str_temp=text.substring(start,stop);
var text_drawing={
content:str_temp,
bold:true,
size:20
};
var c_width=game.stage.measureText(text_drawing).width;
if (c_width<=instance.contentWidth)
{
stop++;
}
else
{
var str_temp=text.substring(start,stop-1);
lines.push(str_temp);
start=stop-1;
}
}
var str_temp=text.substring(start,stop-1);
lines.push(str_temp);
}
this.updateContent=function()
{
var nowTime=(new Date()).getTime();
if (textTime==null) textTime=nowTime;
if (lines==null) initLines();
var charCount=Math.ceil((nowTime-textTime)/charDelay);
var charTotal=0;
if (!!params.talkerPortrait)
{
params.talkerPortrait.type="portrait";
this.drawList.push(params.talkerPortrait);
}
for (var i=linePointer;i<linePointer+3&&i<lines.length;i++)
{
charTotal+=lines[i].length;
}
if (charCount>charTotal) waitConfirm=true;
for (var i=linePointer;i<linePointer+3&&i<lines.length;i++)
{
if (charCount<=lines[i].length)
{
var drawing={
type:"text",
line:i-linePointer,
text:lines[i],
textLen:charCount,
background:null
};
this.drawList.push(drawing);
break;
}
else
{
var drawing={
type:"text",
line:i-linePointer,
text:lines[i],
textLen:lines[i].length,
background:null
};
this.drawList.push(drawing);
charCount-=lines[i].length;
}
}
if (linePointer==0&&!!params.talker)
{
var drawing={
type:"name",
text:params.talker,
color:params.talkerColor
};
this.drawList.push(drawing);
}
if (waitConfirm)
{
this.confirmFlag=Math.floor(nowTime%500/67.5)+1;
}
else
{
this.confirmFlag=0;
}
if (this.getActiveKey()=="enter")
{
if (waitConfirm)
{
waitConfirm=false;
if (linePointer+3<lines.length)
{
linePointer+=3;
textTime=nowTime;
}
else
{
wordPointer++;
lines=null;
linePointer=0;
if (wordPointer>=params.words.length)
{
this.close();
}
else
{
textTime=nowTime;
}
}
}
else
{
textTime=0;
}
}
}
}
| JavaScript |
/**
* @fileOverview Active逻辑活动类源文件
* @author <a href="http://sivory.my.phpcloud.com">sivory</a>
* @version 0
*/
/**
* @class Active逻辑活动类。
* @param {Name.Sivory.Opensea.Game} host 当前逻辑活动类所从属的游戏实例
*
*/
Name.Sivory.Opensea.Active = function(host, id) {
this.$super = OS_Resource;
if(this.$super(host, id) === false) return;
delete this.$super;
var instance = this;
//脚本执行指针,指向当前正在运行的脚本地址,-1为不执行
var actuatorPoint = -1;
//脚本执行队列
var actuators = null;
//可见条件
var enableCondition = null;
//活动是否可见 不可见的活动不截获事件,不显示,不更新状态,不占用地图空间
var enable = true;
this.isEnable = function() {
return enable;
}
//目前的脚本是否正在运行
var running = false;
this.isRunning = function() {
return running;
}
//执行脚本
this.run = function() {
//不能执行一个已经在运行的脚本
if(running) return;
running = true;
actuatorPoint = 0; //转向脚本入口
}
//终止脚本
this.stop = function() {
running = false;
actuatorPoint = -1;
}
//跳转脚本
this.goto = function(index) {
if(!running) return;
actuatorPoint = index;
}
//目前的脚本是否被阻塞(被阻塞也算是正在运行)
var paused = false;
//暂停脚本的执行
this.pause = function() {
paused = true;
}
//恢复脚本的执行
this.resume = function() {
paused = false;
}
//移动结束事件代理
var moveHandler = {};
//获得与触发器相应的事件处理函数
var triggerToHandler = {};
//将要注册在全局事件监听器中的托管,目的是监听对于本活动的confirm事件
var confirmEventHandler = function(sender, params) {
if(!instance.isEnable()) return false;
//确定主角的位置与朝向,以判断是否在激发目前的活动
var row_offset = 0;
var col_offset = 0;
if(sender.direction == 0) row_offset = -1;
else if(sender.direction == 1) col_offset = 1;
else if(sender.direction == 2) row_offset = 1;
else if(sender.direction == 3) col_offset = -1;
var check_col = Math.round(sender.currentPosition.x / host.config.squarewidth) + col_offset;
var check_row = Math.round(sender.currentPosition.y / host.config.squareheight) + row_offset;
var ins_ceil_col = Math.ceil(instance.currentPosition.x / host.config.squarewidth);
var ins_flor_col = Math.floor(instance.currentPosition.x / host.config.squarewidth);
var ins_ceil_row = Math.ceil(instance.currentPosition.y / host.config.squareheight);
var ins_flor_row = Math.floor(instance.currentPosition.y / host.config.squareheight);
if((ins_ceil_col == check_col || ins_flor_col == check_col) && (ins_ceil_row == check_row || ins_flor_row == check_row)) {
instance.run();
return true; //截获此事件 终止遍历
} else {
return false; //不截获此事件 使事件在全局监听器中继续遍历
}
}
triggerToHandler.confirmTrigger = confirmEventHandler;
//将要注册在全局事件监听器中的托管,目的是监听对于本活动的position事件
var positionEventHandler = function(sender, params) {
if(!instance.isEnable()) return false;
//确定主角的位置是否与活动目前的位置相同
var check_col = Math.round(sender.currentPosition.x / host.config.squarewidth);
var check_row = Math.round(sender.currentPosition.y / host.config.squareheight);
var ins_col = Math.round(instance.currentPosition.x / host.config.squarewidth);
var ins_row = Math.round(instance.currentPosition.y / host.config.squareheight);
if(ins_col == check_col && ins_row == check_row) {
instance.run();
return true; //截获此事件 终止遍历
} else {
return false; //不截获此事件 使事件在全局监听器中继续遍历
}
}
triggerToHandler.positionTrigger = positionEventHandler;
//将要注册在全局事件监听器中的托管,目的是监听对于本活动的frame/load事件
var unconditionalEventHandler = function(sender, params) {
if(!instance.isEnable()) return false;
instance.run();
return false; //不截获
}
triggerToHandler.frameTrigger = unconditionalEventHandler;
triggerToHandler.loadTrigger = unconditionalEventHandler;
this.load = function(handler) {
//角色初始位置(以方格记)
this.position = {
x: Number(this.resourceNode.getElementsByTagName("position")[0].getElementsByTagName("x")[0].childNodes[0].nodeValue),
y: Number(this.resourceNode.getElementsByTagName("position")[0].getElementsByTagName("y")[0].childNodes[0].nodeValue)
}
//记录角色上一次逗留的方格的位置
this.lastPosition = {
x: this.position.x * host.config.squarewidth,
y: this.position.y * host.config.squarewidth
}
//记录角色的实时位置
this.currentPosition = {
x: this.position.x * host.config.squarewidth,
y: this.position.y * host.config.squarewidth
}
//角色距上一次逗留的方格的距离
this.distanceFromLastSquare = 0;
this.speed = Number(this.resourceNode.getElementsByTagName("speed")[0].childNodes[0].nodeValue);
this.actor = null;
if(this.resourceNode.getElementsByTagName("bild").length > 0) {
var actorid = this.resourceNode.getElementsByTagName("bild")[0].childNodes[0].nodeValue;
this.actor = OS_Resource.resource.get(actorid);
}
this.direction = Number(this.resourceNode.getElementsByTagName("direction")[0].childNodes[0].nodeValue);
this.mode = this.resourceNode.getElementsByTagName("mode")[0].childNodes[0].nodeValue;
if(this.mode == "auto") {
this.scope = {
colspan: Number(this.resourceNode.getElementsByTagName("scope")[0].getElementsByTagName("colspan")[0].childNodes[0].nodeValue),
rowspan: Number(this.resourceNode.getElementsByTagName("scope")[0].getElementsByTagName("rowspan")[0].childNodes[0].nodeValue)
}
}
this.coverable = eval("(" + this.resourceNode.getElementsByTagName("coverable")[0].childNodes[0].nodeValue + ")");
//加载可见条件
for(var i = 0; i < this.resourceNode.childNodes.length; i++) {
if(this.resourceNode.childNodes[i].nodeType != 1) continue;
if(this.resourceNode.childNodes[i].nodeName == "condition") var conditionNode = this.resourceNode.childNodes[i];
}
if( !! conditionNode) {
for(var i = 0; i < conditionNode.childNodes.length; i++) {
if(conditionNode.childNodes[i].nodeType != 1) continue;
enableCondition = OS_Condition.getInstance(host, this, conditionNode.childNodes[i]);
enable = enableCondition.check();
break;
}
}
//地图位置占用
this.occupy();
//初始化脚本执行器
var logic = this.resourceNode.getElementsByTagName("logic")[0];
if( !! logic) {
//初始化触发器
var triggerGroup = logic.getElementsByTagName("triggerGroup")[0];
for(var i = 0; i < triggerGroup.childNodes.length; i++) {
if(triggerGroup.childNodes[i].nodeType != 1) {
continue;
}
var trigger = triggerGroup.childNodes[i];
var triggerName = trigger.nodeName;
host.status[triggerName].register(triggerToHandler[triggerName]);
}
//初始化脚本队列
actuators = [];
var actuatorGroupNode = logic.getElementsByTagName("actuatorGroup")[0];
var actuatorLoader = OS_Actuator.getInstance(actuatorGroupNode.nodeName);
actuatorLoader.init(host, this, actuatorGroupNode, actuators);
}
this.loaded = true;
handler(this);
}
this.update = function() {
enable = true;
if( !! enableCondition && !enableCondition.check()) {
this.deoccupy();
enable = false;
} else if(!this.coverable) this.occupy();
if(!enable) return;
while( !! running && !paused) {
if(actuatorPoint < actuators.length) {
var func = actuators[actuatorPoint++];
func();
} else {
this.stop();
}
}
}
this.faceto = function(d) {
this.direction = d;
}
this.deoccupy = function() {
if(this.coverable) return;
if(!enable) return;
var map = host.status.activeInterface.world.mapdata;
var position_x = Math.round(this.currentPosition.x);
var position_y = Math.round(this.currentPosition.y);
map[Math.floor(position_y / host.config.squareheight)]
[Math.floor(position_x / host.config.squarewidth)].occupied = false;
map[Math.ceil(position_y / host.config.squareheight)]
[Math.floor(position_x / host.config.squarewidth)].occupied = false;
map[Math.floor(position_y / host.config.squareheight)]
[Math.ceil(position_x / host.config.squarewidth)].occupied = false;
map[Math.ceil(position_y / host.config.squareheight)]
[Math.ceil(position_x / host.config.squarewidth)].occupied = false;
}
this.occupy = function() {
if(this.coverable) return;
if(!enable) return;
var map = host.status.activeInterface.world.mapdata;
var position_x = Math.round(this.currentPosition.x);
var position_y = Math.round(this.currentPosition.y);
map[Math.floor(position_y / host.config.squareheight)]
[Math.floor(position_x / host.config.squarewidth)].occupied = true;
map[Math.ceil(position_y / host.config.squareheight)]
[Math.floor(position_x / host.config.squarewidth)].occupied = true;
map[Math.floor(position_y / host.config.squareheight)]
[Math.ceil(position_x / host.config.squarewidth)].occupied = true;
map[Math.ceil(position_y / host.config.squareheight)]
[Math.ceil(position_x / host.config.squarewidth)].occupied = true;
}
this.forward = function(dis, handlerkey, handler) {
if( !! handler) moveHandler[handlerkey] = handler;
this.deoccupy();
var tempPosition = {
x: this.currentPosition.x,
y: this.currentPosition.y
};
var steplength = this.speed * host.delayTime / 1000;
var distance = dis == undefined ? steplength : dis;
switch(this.direction) {
case 0:
this.currentPosition.y -= distance;
break;
case 1:
this.currentPosition.x += distance;
break;
case 2:
this.currentPosition.y += distance;
break;
case 3:
this.currentPosition.x -= distance;
break;
}
if(!host.status.activeInterface.world.checkActivePosition(this)) {
this.currentPosition = tempPosition;
distance = 0;
}
this.distanceFromLastSquare += distance;
this.occupy();
}
this.back = function(dis, handlerkey, handler) {
if( !! handler) moveHandler[handlerkey] = handler;
this.deoccupy();
var tempPosition = {
x: this.currentPosition.x,
y: this.currentPosition.y
};
var steplength = this.speed * host.delayTime / 1000;
var distance = dis == undefined ? steplength : dis;
switch(this.direction) {
case 0:
this.currentPosition.y += distance;
break;
case 1:
this.currentPosition.x -= distance;
break;
case 2:
this.currentPosition.y -= distance;
break;
case 3:
this.currentPosition.x += distance;
break;
}
if(!host.status.activeInterface.world.checkActivePosition(this)) {
this.currentPosition = tempPosition;
distance = 0;
}
this.distanceFromLastSquare -= distance;
this.occupy();
}
this.isInPosition = function() {
if(this.distanceFromLastSquare == 0) {
for(var index in moveHandler) {
var func = moveHandler[index];
func();
}
moveHandler = {};
return true;
}
var limit = 0;
if(this.direction == 1 || this.direction == 3) {
limit = host.config.squarewidth;
} else {
limit = host.config.squareheight;
}
var steplength = this.speed * host.delayTime / 1000;
if(this.distanceFromLastSquare > 0 && limit - this.distanceFromLastSquare < steplength) {
this.forward(limit - this.distanceFromLastSquare);
this.distanceFromLastSquare = 0;
this.currentPosition.x = Math.round(this.currentPosition.x);
this.currentPosition.y = Math.round(this.currentPosition.y);
this.lastPosition.x = this.currentPosition.x;
this.lastPosition.y = this.currentPosition.y;
for(var index in moveHandler) {
var func = moveHandler[index];
func();
}
moveHandler = {};
return true;
}
if(this.distanceFromLastSquare < 0 && this.distanceFromLastSquare + limit < steplength) {
this.back(this.distanceFromLastSquare + limit);
this.distanceFromLastSquare = 0;
this.currentPosition.x = Math.round(this.currentPosition.x);
this.currentPosition.y = Math.round(this.currentPosition.y);
this.lastPosition.x = this.currentPosition.x;
this.lastPosition.y = this.currentPosition.y;
for(var index in moveHandler) {
var func = moveHandler[index];
func();
}
moveHandler = {};
return true;
}
return false;
}
this.drawSelf = function() {
if(!enable) return;
if(!this.actor) return;
var directions = ["up", "right", "down", "left"];
var steps = [2, 1, 2, 3];
var offset = this.currentPosition.x % (host.config.squarewidth * 2) + this.currentPosition.y % (host.config.squarewidth * 2);
offset = Math.floor((offset + 8) % (host.config.squarewidth * 2) / 16);
var index = directions[this.direction] + steps[offset];
var currentFrame = this.actor.actions[index];
host.stage.draw(currentFrame, this.currentPosition.x, this.currentPosition.y);
}
};
OS_Resource.Builder.put("active", OS_Active); | JavaScript |
//脚本集合:actuatorGroup
var dowithActuatorGroup=function(host,active,node,actuators)
{
for (var i=0;i<node.childNodes.length;i++)
{
if (node.childNodes[i].nodeType!=1)
{
continue;
}
var actuatorNode=node.childNodes[i];
var actuatorLoader=OS_Actuator.getInstance(actuatorNode.nodeName);
if (!!actuatorLoader) actuatorLoader.init(host,active,actuatorNode,actuators);
}
}
OS_Actuator.list.put("actuatorGroup",dowithActuatorGroup);
//playeffect脚本
var dowithPlayEffect=function(host,active,node,actuators)
{
var sourceid=node.getElementsByTagName("source")[0].childNodes[0].nodeValue;
var targetid=node.getElementsByTagName("target")[0].childNodes[0].nodeValue;
var target=null;
if (targetid=="self") target=active;
else target=OS_Resource.resource.get(targetid);
var func=function(){
var effect_temp=OS_Resource.resource.get(sourceid);
position_y=target.currentPosition.y/host.config.squareheight;
position_x=target.currentPosition.x/host.config.squarewidth;
host.status.activeInterface.playEffect(effect_temp,position_y,position_x);
};
actuators.push(func);
}
OS_Actuator.list.put("playEffect",dowithPlayEffect);
//move操作
var dowithMove=function(host,active,node,actuators)
{
//确定方向
var direction=node.getAttribute("direction");
directions={up:0,right:1,down:2,left:3}
var faceTo=directions[direction];
//确定目标
var targetid=node.getElementsByTagName("target")[0].childNodes[0].nodeValue;
var target=null;
if (targetid=="self")
{
target=active;
}
else if (targetid=="lead")
{
target=host.status.leadingRole;
}
else
{
target=OS_Resource.resource.get(targetid);
}
var func=function()
{
target.faceto(faceTo);
target.forward(undefined,"resumeactive",function(){
active.resume();//恢复脚本的执行
});
active.pause();//阻塞脚本队列的执行
};
actuators.push(func);
}
OS_Actuator.list.put("move",dowithMove);
//talk操作
var dowithTalk=function(host,active,node,actuators)
{
if (!!node.getElementsByTagName("talker")[0])
{
var talker=node.getElementsByTagName("talker")[0].childNodes[0].nodeValue;
var talkerColor=node.getElementsByTagName("talker")[0].getAttribute("color");
}
var talkerPortrait=null;
if (!!node.getElementsByTagName("portrait")[0])
{
talkerPortrait={};
talkerPortrait.image=OS_Resource.resource.get(node.getElementsByTagName("portrait")[0].getElementsByTagName("source")[0].childNodes[0].nodeValue).getImage();
talkerPortrait.position=node.getElementsByTagName("portrait")[0].getElementsByTagName("position")[0].childNodes[0].nodeValue;
talkerPortrait.height=320;
}
var wordlist=node.getElementsByTagName("word");
var words=[];
for (var i=0;i<wordlist.length;i++)
{
words.push(wordlist[i].childNodes[0].nodeValue);
}
var func=function()
{
var mydirections=[2,3,0,1];
var directionTemp=active.direction;
var wordsFinal=[];
active.direction=mydirections[host.status.leadingRole.direction];
for (var i=0;i<words.length;i++)
{
var textTemp=words[i];
var vs=textTemp.indexOf("{=");
while (vs>-1)
{
var ve=textTemp.indexOf("}",vs);
textTemp=textTemp.slice(0,vs)+host.status.V.get(textTemp.slice(vs+2,ve))+textTemp.slice(ve+1);
var vs=textTemp.indexOf("{=");
}
if (!!talker)
{
wordsFinal.push(talker+":"+textTemp);
}
else
{
wordsFinal.push(textTemp);
}
}
var talk={
words:wordsFinal,
talker:talker,
talkerColor:talkerColor,
talkerPortrait:talkerPortrait,
callback:function(){
active.direction=directionTemp;
active.resume();
host.status.activeInterface.resume();
}
};
var dialog=new OS_TalkDialog(host,host.status.activeInterface,host.status.activeInterface.getWinRes(),talk);
dialog.open();
host.status.activeInterface.pause();
active.pause();
};
actuators.push(func);
}
OS_Actuator.list.put("talk",dowithTalk);
//delay操作
var dowithDelay=function(host,active,node,actuators)
{
var time=Number(node.getAttribute("time"));
func=function()
{
setTimeout(function(){
active.resume()
},time);
active.pause();
}
actuators.push(func);
}
OS_Actuator.list.put("delay",dowithDelay);
//select操作
var dowithSelect=function(host,active,node,actuators)
{
var key=node.getAttribute("key");
var text=node.getElementsByTagName("text")[0].childNodes[0].nodeValue;
var options=[];
var optionNodes=node.getElementsByTagName("option");
for (var i=0;i<optionNodes.length;i++)
{
var optionNode=optionNodes[i];
var optionText=optionNode.getElementsByTagName("text")[0].childNodes[0].nodeValue;
var optionValue=optionNode.getAttribute("value");
var option={text:optionText,value:optionValue};
options.push(option);
}
var func=function()
{
var mydirections=[2,3,0,1];
var directionTemp=active.direction;
active.direction=mydirections[host.status.leadingRole.direction];
var select={
text:text,
key:key,
options:options,
callback:function()
{
active.direction=directionTemp;
active.resume();
host.status.activeInterface.resume();
}
};
var dialog=new OS_SelectDialog(host,host.status.activeInterface,host.status.activeInterface.getWinRes(),select);
dialog.open();
host.status.activeInterface.pause();
active.pause();
}
actuators.push(func);
}
OS_Actuator.list.put("select",dowithSelect);
//if操作
var dowithIf=function(host,active,node,actuators)
{
var thenIndex=0;
var elseIndex=0;
var nextIndex=0;
var condition=null;
var conditionNode=node.getElementsByTagName("condition")[0];
for (var i=0;i<conditionNode.childNodes.length;i++)
{
if (conditionNode.childNodes[i].nodeType!=1) continue;
condition=OS_Condition.getInstance(host,active,conditionNode.childNodes[i]);
break;
}
var funcIf=function()
{
if (condition.check()) active.goto(thenIndex);
else active.goto(elseIndex);
}
var funcEndIf=function()
{
active.goto(nextIndex);
}
actuators.push(funcIf);
thenIndex=actuators.length;
var thenNode=node.getElementsByTagName("then")[0];
for (var i=0;i<thenNode.childNodes.length;i++)
{
if (thenNode.childNodes[i].nodeType!=1) continue;
var actuatorNode=thenNode.childNodes[i];
var actuatorLoader=OS_Actuator.getInstance(actuatorNode.nodeName);
if (!!actuatorLoader) actuatorLoader.init(host,active,actuatorNode,actuators);
actuators.push(funcEndIf);
break;
}
elseIndex=actuators.length;
for (var i=0;i<node.childNodes.length;i++)
{
if (node.childNodes[i].nodeType!=1) continue;
if (node.childNodes[i].nodeName=="else")
var elseNode=node.childNodes[i];
}
if (!!elseNode)
{
for (var i=0;i<elseNode.childNodes.length;i++)
{
if (elseNode.childNodes[i].nodeType!=1) continue;
var actuatorNode=elseNode.childNodes[i];
var actuatorLoader=OS_Actuator.getInstance(actuatorNode.nodeName);
if (!!actuatorLoader) actuatorLoader.init(host,active,actuatorNode,actuators);
actuators.push(funcEndIf);
break;
}
}
nextIndex=actuators.length;
}
OS_Actuator.list.put("if",dowithIf);
//setVariable操作
var dowithSetVariable=function(host,active,node,actuators)
{
var key=node.getAttribute("key");
var value=node.getAttribute("value");
var func=function()
{
host.status.V.put(key,value);
}
actuators.push(func);
}
OS_Actuator.list.put("setVariable",dowithSetVariable);
//fight操作
var dowithFight=function(host,active,node,actuators)
{
var battleid=node.childNodes[0].nodeValue;
var func=function()
{
host.status.activeInterface.pause();
active.pause();
var battle=OS_Resource.resource.get(battleid);
host.loopEndHooks.push(function(){
battle.callback=function()
{
active.resume();
}
battle.show();
});
}
actuators.push(func);
}
OS_Actuator.list.put("fight",dowithFight);
//while操作
var dowithWhile=function(host,active,node,actuators)
{
var conditionIndex=0;
var doIndex=0;
var nextIndex=0;
var condition=null;
var conditionNode=node.getElementsByTagName("condition")[0];
for (var i=0;i<conditionNode.childNodes.length;i++)
{
if (conditionNode.childNodes[i].nodeType!=1) continue;
condition=OS_Condition.getInstance(host,active,conditionNode.childNodes[i]);
break;
}
var funcCondition=function()
{
if (condition.check()) active.goto(doIndex);
else active.goto(nextIndex);
}
var funcEndDo=function()
{
active.goto(conditionIndex);
}
var conditionIndex=actuators.length;
actuators.push(funcCondition);
var doIndex=actuators.length;
var doNode=node.getElementsByTagName("do")[0];
for (var i=0;i<doNode.childNodes.length;i++)
{
if (doNode.childNodes[i].nodeType!=1) continue;
var actuatorNode=doNode.childNodes[i];
var actuatorLoader=OS_Actuator.getInstance(actuatorNode.nodeName);
if (!!actuatorLoader) actuatorLoader.init(host,active,actuatorNode,actuators);
actuators.push(funcEndDo);
break;
}
nextIndex=actuators.length;
}
OS_Actuator.list.put("while",dowithWhile);
//跳转脚本
var dowithJump=function(host,active,node,actuators)
{
var sceneid=node.getElementsByTagName("toscene")[0].childNodes[0].nodeValue;
var positionx=Number(node.getElementsByTagName("position")[0].getElementsByTagName("x")[0].childNodes[0].nodeValue);
var positiony=Number(node.getElementsByTagName("position")[0].getElementsByTagName("y")[0].childNodes[0].nodeValue);
var func=function()
{
host.changeInterface(sceneid,"scene");
host.status.leadingRole.currentPosition.x=positionx*host.config.squarewidth;
host.status.leadingRole.currentPosition.y=positiony*host.config.squarewidth;
host.status.leadingRole.distanceFromLastSquare=0;
host.loopStartHooks.push(function(){host.status.leadingRole.occupy();});
}
actuators.push(func);
}
OS_Actuator.list.put("jump",dowithJump);
//渐变脚本
var dowithGradual=function(host,active,node,actuators)
{
var red=Number(node.getAttribute("r"));
var green=Number(node.getAttribute("g"));
var blue=Number(node.getAttribute("b"));
var alpha=Number(node.getAttribute("a"));
var duration=Number(node.getAttribute("d"));
var func=function()
{
var gradualTemp={};
gradualTemp.startTime=(new Date()).getTime();
gradualTemp.duration=duration;
gradualTemp.fromR=host.status.activeInterface.filter.r;
gradualTemp.fromG=host.status.activeInterface.filter.g;
gradualTemp.fromB=host.status.activeInterface.filter.b;
gradualTemp.fromA=host.status.activeInterface.filter.a;
gradualTemp.toR=red;
gradualTemp.toG=green;
gradualTemp.toB=blue;
gradualTemp.toA=alpha;
gradualTemp.callback=function()
{
active.resume();
host.status.activeInterface.resume();
}
host.status.activeInterface.gradual=gradualTemp;
host.status.activeInterface.pause();
active.pause();
}
actuators.push(func);
}
OS_Actuator.list.put("gradual",dowithGradual);
//插图脚本
var dowithIllustration=function(host,active,node,actuators)
{
var dowhat=node.getElementsByTagName("do")[0].textContent;
if (dowhat=="clear")
{
var func=function()
{
host.status.activeInterface.illustration=null;
}
}
else if (dowhat=="draw")
{
var source=node.getElementsByTagName("source")[0].textContent;
var func=function()
{
host.status.activeInterface.illustration=source;
}
}
actuators.push(func);
}
OS_Actuator.list.put("illustration",dowithIllustration);
//成员加入脚本
var dowithAppend=function(host,active,node,actuators)
{
var memberName=node.getAttribute("name");
var func=function()
{
host.status.team.append(memberName);
var params={
position:"center",
width:160,
height:90,
words:[memberName+" 加入队伍!"],
callback:function(){
active.resume();
host.status.activeInterface.resume();
}
};
var dialog=new OS_TalkDialog(host,host.status.activeInterface,host.status.activeInterface.getWinRes(),params);
dialog.open();
host.status.activeInterface.pause();
active.pause();
}
actuators.push(func);
}
OS_Actuator.list.put("append",dowithAppend);
//成员离开脚本
var dowithLeave=function(host,active,node,actuators)
{
var memberName=node.getAttribute("name");
var func=function()
{
host.status.team.leave(memberName);
var params={
position:"center",
width:140,
height:80,
words:[memberName+" 离开队伍!"],
callback:function(){
active.resume();
host.status.activeInterface.resume();
}
};
var dialog=new OS_TalkDialog(host,host.status.activeInterface,host.status.activeInterface.getWinRes(),params);
dialog.open();
host.status.activeInterface.pause();
active.pause();
}
actuators.push(func);
}
OS_Actuator.list.put("leave",dowithLeave);
//游戏结束脚本
var dowithGameover=function(host,active,node,actuators)
{
var func=function()
{
host.loopEndHooks.push(function(){
host.changeInterface(host.config.entryInterface,"menu");
});
}
actuators.push(func);
}
OS_Actuator.list.put("gameOver",dowithGameover);
| JavaScript |
function OS_Dialog(game,interface,winres,params)
{
var activeKey=null;
var width=500;
if (!!params.width) width=params.width;
var height=120;
if (!!params.height) height=params.height;
var currentHeight=0;
var bottom=20;
var top=null;
if (params.position=="top") {bottom=null;top=20;}
else if (params.position=="bottom") {bottom=20;top=null;}
else if (params.position=="center") {bottom=null;top=null;}
var duration=200;
var startTime=0;
var closingTime=0;
var paddingL=30;
var paddingT=15;
var lineHeight=30;
var fontSize=20;
var paddingLp=10;//肖像边距
this.contentWidth=width-paddingL*2;
this.confirmFlag=0;
this.drawList=[];
var callback=params.callback;
this.setCallback=function(cb)
{
callback=cb;
}
this.getHeight=function()
{
return height;
}
this.getPaddingT=function()
{
return paddingT;
}
this.getLineHeight=function()
{
return lineHeight;
}
this.interceptKey=function()
{
activeKey=null;
var keys=["esc","enter","left","right","up","down","space"];
for (var index in keys)
{
var key=keys[index];
if (!!game.status.checkKeyPressed(key))
{
activeKey=key;
}
}
}
this.getActiveKey=function()
{
return activeKey;
}
this.open=function()
{
interface.setActiveDialog(this);
startTime=(new Date()).getTime();
closingTime=0;
}
this.close=function()
{
closingTime=(new Date()).getTime();
}
this.update=function()
{
this.drawList.splice(0);
var timecost=(new Date()).getTime()-startTime;
//如果对话框正要关闭
if (closingTime>0)
{
timecost=(new Date()).getTime()-closingTime;
if (timecost<duration)
{
currentHeight=height*Math.sin(Math.PI*0.5*(1-timecost/duration));
}
else
{
interface.setActiveDialog(null);
if (!!callback)
{
callback();
}
}
}
//对话框正要开启
else if (timecost<duration)
{
var timecost=(new Date()).getTime()-startTime;
currentHeight=height*Math.sin(Math.PI*0.5*timecost/duration);
}
//更新对话框中的内容
else
{
currentHeight=height;
this.updateContent();
}
}
this.updateContent=function()
{
game.error("未被重载的抽象函数");
}
this.drawSelf=function()
{
var dleft=game.config.width*0.5-width*0.5;
var dtop=0;
if (!!top) dtop=top;//居上
else if (!!bottom) dtop=game.config.height-bottom-height*0.5-currentHeight*0.5;//居下
else dtop=game.config.height*0.5-currentHeight*0.5;//居中
game.stage.drawWindow(winres,dleft,dtop,width,currentHeight,this.confirmFlag);
for (var i=0;i<this.drawList.length;i++)
{
var drawing=this.drawList[i];
switch(drawing.type)
{
case "text":
var text_temp=drawing.text.substr(0,drawing.textLen);
var text_drawing={
content:text_temp,
bold:true,
maxWidth:this.contentWidth,
size:fontSize,
color:drawing.disable?"rgba(255,255,255,0.5)":"#eee",
shadow:{offsetX:1,offsetY:1,blur:1,color:"#000"},
background:drawing.background
};
game.stage.write(text_drawing,dleft+paddingL,dtop+paddingT+drawing.line*lineHeight);
break;
case "name":
var text_drawing={
content:drawing.text,
bold:true,
size:fontSize,
color:drawing.color,
shadow:{offsetX:1,offsetY:1,blur:1,color:"#000"},
};
game.stage.write(text_drawing,dleft+paddingL,dtop+paddingT);
break;
case "portrait":
var sheight=drawing.image.height;
var swidth=drawing.image.width;
var pheight=drawing.height;
var pwidth=swidth*pheight/sheight;
var ptop=dtop-pheight;
var pleft=dleft+paddingLp;
if (drawing.position=="right")
{
pleft=dleft+width-paddingLp-pwidth;
}
game.stage.getContext().drawImage(
drawing.image,
0,0,swidth,sheight,
pleft,ptop,pwidth,pheight
);
break;
}
}
}
}
| JavaScript |
/**
* @fileOverview Castle命名空间配置文件
* @author <a href="http://sivory.my.phpcloud.com">Sivory</a>
* @version 0
*/
(function() {
if(!Name)
/**
* @namespace Name根域名命名空间
*/
Name = {};
if(!Name.Sivory)
/**
* @namespace Sivory的命名空间
*/
Name.Sivory = {};
if(!Name.Sivory.Castle)
/**
* @namespace Castle项目的命名空间
*/
Name.Sivory.Castle = {};
if(!Name.Sivory.Castle.Util)
/**
* @namespace Castle项目中的公用方法的命名空间
*/
Name.Sivory.Castle.Util = {};
if(!Name.Sivory.Castle.Core)
/**
* @namespace Castle项目中的内核的命名空间
*/
Name.Sivory.Castle.Core = {};
if(!Name.Sivory.Castle.Editor)
/**
* @namespace Castle项目中的设计器的命名空间
*/
Name.Sivory.Castle.Editor = {};
})(); | JavaScript |
function OS_Effect(host,id)
{
this.$super=OS_Sprite;
if (this.$super(host,id)===false) return;
delete this.$super;
this.timeLine={};
this.length=0;
this.loadTimestamps=function()
{
var timestamps=this.resourceNode.getElementsByTagName("timeline")[0].getElementsByTagName("timestamp");
this.length=timestamps.length;
for (var i=0;i<timestamps.length;i++)
{
var timestamp=timestamps[i];
var index=Number(timestamp.getAttribute("index"));
var frameid=timestamp.childNodes[0].nodeValue;
this.timeLine[index]=OS_Resource.resource.get(frameid);
}
}
}
| JavaScript |
/**
* @fileOverview Castle游戏事件类
* @author <a href="http://sivory.my.phpcloud.com">Sivory</a>
* @version 0.0.1
*/
(function() {
/** @exports _Class as Name.Sivory.Castle.Core.Event */
var _Class =
/**
* @class 游戏的事件类,托管游戏中事件的注册、触发等操作。
* @param {Name.Sivory.Castle.Core.Game} 游戏实例对象,参见{@link Name.Sivory.Castle.Core.Game}
* @author <a href="http://sivory.my.phpcloud.com">Sivory</a>
* @version 0.0.1
*/
Name.Sivory.Castle.Core.Event = function(g) {
/**
* @private
* @field
* @type Name.Sivory.Castle.Core.Game
* @description 游戏实例的引用
* @since 0.0.1
*/
this.game = g;
/**
* @private
* @field
* @type Object
* @description 游戏事件列表的集合,它记录的是与事件相对应的索引以及此索引下的事件处理函数的列表。
* @since 0.0.1
*/
this.triggerArraySet = {};
};
/**
* @public
* @function
* @description 注册游戏事件
* @param {String} type 游戏事件的类型
* @param {Function(params)} handler 游戏事件的处理函数,将负责接收参数params,此参数中有事件的详细信息
* @since 0.0.1
*/
_Class.prototype.register = function(type, handler) {
if(this.triggerArraySet[type] === null || this.triggerArraySet[type] === undefined) {
this.triggerArraySet[type] = [];
}
this.triggerArraySet[type].push(handler);
};
/**
* @public
* @function
* @description 触发游戏事件
* @param {String} type 游戏事件的类型
* @param {String} sender 游戏事件的发送者
* @param {Object} params 游戏事件的详细参数
* @since 0.0.1
*/
_Class.prototype.trigger = function(type, sender, params) {
params.gameIns = this.game;
params.sender = sender;
//遍历执行游戏事件处理函数
if(this.triggerArraySet.hasOwnProperty(type)) {
for(var i = 0; i < this.triggerArraySet[type].length; i++) {
var handler = this.triggerArraySet[type][i];
handler(params);
}
}
};
/**
* @public
* @function
* @description 清除游戏事件的处理函数
* @param {String} type 可选参数,将清除type类型事件中相应的处理函数。若留空,则会清除所有类型事件的所有处理函数。
* @param {Function} handler 可选参数,将清除事件中指定的处理函数。若留空,则会清除该事件下所有处理函数。
* @since 0.0.1
*/
_Class.prototype.clear = function(type, handler) {
if(typeof type === "function" || type === null || type === undefined) {
//清除所有事件的所有处理函数
for(var index in this.triggerArraySet) {
this.triggerArraySet[index].splice(0);
delete this.triggerArraySet[index];
}
} else if(handler === null || handler === undefined) {
//清除指定事件的所有处理函数
if(this.triggerArraySet.hasOwnProperty(type) && typeof this.triggerArraySet[type].splice === "function") {
this.triggerArraySet[type].splice(0);
}
} else {
//清除指定事件的指定处理函数
if(this.triggerArraySet.hasOwnProperty(type) && typeof this.triggerArraySet[type].splice === "function") {
var index=0;
for(var i = 0; i < this.triggerArraySet[type]; i++)
if(this.triggerArraySet[type][i] === handler) {
index=i;
break;
}
this.triggerArraySet[type].splice(index,1);
}
}
}
})(); | JavaScript |
function OS_Image(host,id)
{
this.$super=OS_Resource;
if (this.$super(host,id)===false) return;
delete this.$super;
var image=new Image();
this.load=function(handler)
{
var src=this.resourceNode.getElementsByTagName("link")[0].childNodes[0].nodeValue;
var instance=this;
image.onload=function(){
instance.loaded=true;
handler(instance);
};
image.src=src;
}
this.getImage=function()
{
return image;
}
}
OS_Resource.Builder.put("image",OS_Image);
| JavaScript |
/**
* @fileOverview Castle游戏实例中的钩子类Hook源代码
* @author <a href="http://sivory.my.phpcloud.com">Sivory</a>
* @version 0.0.1
*/
(function() {
/** @exports _Class as Name.Sivory.Castle.Core.Debug */
var _Class =
/**
* @class Castle游戏实例中的钩子类。它本质上是一个函数队列,不过此队列中的函数仅会被执行一遍,执行一遍后队列将被清空。
* @author <a href="http://sivory.my.phpcloud.com">Sivory</a>
* @version 0.0.1
*/
Name.Sivory.Castle.Util.Hook = function() {
/**
* @private
* @field
* @type Array
* @description 记录函数用的队列
* @since 0.0.1
*/
this.funcList = [];
};
/**
* @public
* @function
* @description 向钩子中添加函数
* @param {Function} func 将在钩子中被执行的函数
* @since 0.0.1
*/
_Class.prototype.add = function(func) {
this.funcList.push(func);
};
/**
* @public
* @function
* @description 执行钩子中的函数,此操作是一次性的,运行后所有函数将被删除。
* @since 0.0.1
*/
_Class.prototype.run = function() {
//遍历队列并调用其中函数
for(var i = 0; i < this.funcList.length; i++) {
var func = this.funcList[i];
func();
}
//清空队列
this.funcList.splice(0);
};
})(); | JavaScript |
//代表脚本语句
function OS_Actuator(func)
{
this.init=function(host,active,actuatorNode,actuators)
{
func(host,active,actuatorNode,actuators);
}
}
OS_Actuator.list=new OS_HashTable();
//取得一类语句
OS_Actuator.getInstance=function(tagname)
{
if (!OS_Actuator.list.containsKey(tagname)) return null;
var func=OS_Actuator.list.get(tagname);
return new OS_Actuator(func);
}
| JavaScript |
function OS_Music(host,id)
{
this.$super=OS_Resource;
if (this.$super(host,id)===false) return;
delete this.$super;
var audio=new Audio();
audio.loop=false;
audio.preload=true;
audio.audoplay=false;
this.load=function(handler)
{
var instance=this;
audio.addEventListener("canplay",function(){
instance.loaded=true;
handler(instance);
});
audio.src=this.resourceNode.getElementsByTagName("link")[0].textContent;
}
this.setLoop=function(isLoop){
audio.loop=isLoop;
}
this.play=function(){
audio.play();
}
this.pause=function(){
audio.pause();
}
this.stop=function()
{
audio.pause();
audio.currentTime=0;
}
this.getVolume=function()
{
return Math.round(audio.volume*100);
}
this.setVolume=function(value)
{
if (value>100) value=100;
if (value<0) value=0;
audio.volume=value/100;
}
this.setHandler=function(type,handler){
audio.addEventListener(type,handler);
}
}
OS_Resource.Builder.put("music",OS_Music);
| JavaScript |
/**
* @fileOverview Castle游戏状态机类源文件
* @author <a href="http://sivory.my.phpcloud.com">Sivory</a>
* @version 0.0.0
*/
(function() {
/** @exports _Class as Name.Sivory.Castle.Core.Status */
var _Class =
/**
* @class Castle游戏实例类Game。它托管着一个游戏集成环境,保证游戏各部件的协同工作。游戏的主循环在此类中托管,另外,Game还负责游戏不同界面间的切换。
* @param {Name.Sivory.Castle.Core.Game} game 游戏实例对象,参见{@link Name.Sivory.Castle.Core.Game}
* @author <a href="http://sivory.my.phpcloud.com">Sivory</a>
* @version 0.0.1
*/
Name.Sivory.Castle.Core.Status = function(g) {
/**
* @private
* @field
* @type Name.Sivory.Castle.Core.Game
* @description 游戏实例的引用
* @since 0.0.1
*/
this.game = g;
/**
* @public
* @field
* @type Name.Sivory.Castle.Core.Interface
* @description 游戏中当前处于活动状态的界面
* @since 0.0.1
*/
this.activeInterface = null;
/**
* @public
* @field
* @type Name.Sivory.Castle.Util.HashTable
* @description 游戏中的用户数据(用户可见)
* @since 0.0.1
*/
this.userData = new Name.Sivory.Castle.Util.HashTable();
/**
* @public
* @field
* @type Name.Sivory.Castle.Util.HashTable
* @description 游戏中的内核数据(用户不可见)
* @since 0.0.1
*/
this.systemData = new Name.Sivory.Castle.Util.HashTable();
/**
* @public
* @field
* @type Name.Sivory.Castle.Util.HashTable
* @description 游戏运行时的键盘状态
* @since 0.0.1
*/
this.keyboardStatus = new Name.Sivory.Castle.Util.HashTable();
/**
* @public
* @field
* @type Name.Sivory.Castle.Core.Active
* @description 游戏中的主角活动体
* @since 0.0.1
*/
this.leadingRole = null;
/**
* @public
* @field
* @type Array
* @description 游戏中的配角活动体集合
* @since 0.0.1
*/
this.supportingRoles = [];
/**
* @public
* @field
* @type Name.Sivory.Castle.Core.Team
* @description 游戏中的主角属性托管单元
* @since 0.0.1
*/
this.team = null;
/**
* @public
* @field
* @type Name.Sivory.Castle.Core.Event
* @description 游戏事件托管
* @since 0.0.1
*/
this.event = new Name.Sivory.Castle.Core.Event();
};
/**
* @public
* @function
* @description 游戏事件托管
* @param {String} key 设置key键已被按下
* @since 0.0.1
*/
_Class.prototype.getKeyboardStatus = function(key) {
if(keyboardStatus.containsKey(key)) {
return keyboardStatus.get(key);
} else {
return false;
}
};
_CLass.prototype.setKeyboardStatus = function(key, pressed) {
keyboardStatus.put(key, pressed);
};
this.resetKeyboardStatus = function() {
keyboardStatus.clear();
};
this.checkKeyPressed = function(key) {
var keyStatus = game.status.getKeyboardStatus(key);
var time = (new Date()).getTime();
if(!keyStatus) return false;
if(keyStatus < time) {
this.setKeyboardStatus(key, time + game.config.keyDelay);
return keyStatus;
}
return false;
}
this.checkKeyHold = function(key) {
var keyStatus = game.status.getKeyboardStatus(key);
if(!keyStatus) return false;
return keyStatus;
}
this.saveToLocal = function() {
//存储场景数据
var sceneKey = "movcastle.com|" + game.config.gameKey + "|scene";
var sceneData = this.activeInterface.encode();
localStorage.setItem(sceneKey, sceneData);
//存储全局变量
var globalKey = "movcastle.com|" + game.config.gameKey + "|global";
var globalData = this.V.encode();
localStorage.setItem(globalKey, globalData);
//存储角色数据
var teamKey = "movcastle.com|" + game.config.gameKey + "|team";
var teamData = this.team.encode();
localStorage.setItem(teamKey, teamData);
}
this.loadFromLocal = function() {
//读取场景数据
var sceneKey = "movcastle.com|" + game.config.gameKey + "|scene";
var sceneData = localStorage.getItem(sceneKey);
this.activeInterface.decode(sceneData);
//读取全局变量
var globalKey = "movcastle.com|" + game.config.gameKey + "|global";
var globalData = localStorage.getItem(globalKey);
this.V.decode(globalData);
//存储角色数据
var teamKey = "movcastle.com|" + game.config.gameKey + "|team";
var teamData = localStorage.getItem(teamKey);
this.team.decode(teamData);
}
this.reset = function() {
this.V.clear();
this.leadingRole = null;
this.supportingRoles.splice(0);
this.team = null;
this.clearEventHandlers();
this.resetKeyboardStatus();
}
/**
* @function
* @public
* @description 切换界面的方法。当游戏需要进行界面切换时,调用此方法。
* @param {String} id 界面资源的id,此id需要在游戏源中声明。
* @param {String} type 界面资源的类型,目前有四个可选值,分别是"scene","menu","battle","load",前三种分别是三种基本界面类型,load表示读取存档,此时将会加载scene类型的界面(因为保存的时候必然是在场景中进行保存操作的,而战斗中则不能进行保存操作,保存菜单界面也根本没有意义)
* @param {Boolean} cbgm 是否切换当前的背景音乐
* @since 0.0.1
*/
this.changeInterface = function(id, type, cbgm) {
//在当前循环体结束时打开加载画面
instance.loopEndHooks.push(function() {
instance.loader.start();
});
//停止主循环
loopStoped = true;
//清空资源集合
instance.resource.clear();
//清空状态机中注册的事件
instance.status.clearEventHandlers();
//当要读取进度时
if(type == "load") {
var sceneKey = "movcastle.com|" + instance.config.gameKey + "|scene";
//
var sceneStr = localStorage.getItem(sceneKey);
if(!sceneStr) {
throw "存档读取错误";
} else {
var sceneData = eval("(" + sceneStr + ")");
var interfaceBuilder = OS_Resource.Builder.get("scene");
var newInterface = new interfaceBuilder(instance, sceneData.sceneid);
var activeBuilder = OS_Resource.Builder.get("active");
new activeBuilder(instance, sceneData.activeid);
instance.loopEndHooks.push(function() {
instance.status.loadFromLocal();
});
}
} else {
var interfaceBuilder = OS_Resource.Builder.get(type);
var newInterface = new interfaceBuilder(instance, id);
}
newInterface.show();
OS_Resource.loadResource(instance, instance.loader, function() {
instance.status.loadTrigger.active(); //触发加载完毕事件
instance.loader.stop(); //停止加载器界面
if(cbgm == null || cbgm == true) newInterface.playBGM(); //播放背景音乐
delete window.$starttime;
//启动主循环
instance.mainLoop();
});
};
this.createInterface = function() {
//新建一个入口界面
var entry = new OS_Menu(this, this.config.entryInterface);
this.loader.start();
entry.show();
OS_Resource.loadResource(this, this.loader, function() {
this.loader.stop();
entry.playBGM();
this.mainLoop();
});
}
})(); | JavaScript |
function OS_BattlerState(){
var name=null; //状态名称
var num=1; //作用回合次数
this.test=function(term)
{
if(term==name)
return true;
else
return false;
}
this.setName=function(varName)
{
name=varName;
}
this.setNum=function(varNum)
{
num=Number(varNum);
}
this.getName=function()
{
return name;
}
this.getNum=function()
{
return num;
}
} | JavaScript |
/**
* @fileOverview 游戏实例资源管理器的源文件
* @author <a href="http://sivory.my.phpcloud.com">Sivory</a>
* @version 0
*/
/**
* @class 游戏资源管理器类。对游戏中的资源进行整合管理,并负责向游戏内核提供资源。
* @author <a href="http://sivory.my.phpcloud.com">Sivory</a>
* @version 0
*/
Name.Sivory.Opensea.Resource=function()
{
var instance = this;
/**
* @field
* @private
* @description 资源哈希表
* @type Name.Sivory.Opensea.HashTable
* @since 0
*/
this.resource = new Name.Sivory.Opensea.HashTable();
/**
* @field
* @private
* @description 资源加载队列
* @type Array
* @since 0
*/
this.loadingQueue = [];
/**
* @function
* @public
* @description 将资源放入集合中
* @param {String} key 资源在托管器中的索引
* @param {Name.Sivory.Opensea.ResourceBase} resource 资源对象
* @since 0
*/
this.put = function(key,resource){
instance.resource.put(key,resource);
instance.loadingQueue.push(resource);
}
/**
* @function
* @public
* @description 从集合中取得资源
* @param {String} key 目标资源的索引
* @returns {Name.Sivory.Opensea.ResourceBase} 资源对象
* @since 0
*/
this.get=function(key){
return instance.resource.get(key);
}
this.containsKey=function(key){
return instance.resource.containsKey(key);
}
/**
* @function
* @public
* @description 清空资源集合
* @since 0
*/
this.clear=function(){
instance.resource.clear();
}
/**
* @function
* @public
* @description 加载所有在集合中的资源
* @since 0
*/
this.loadAll=function(game,callback){
var mustLoad=game.config.mustLoad;
for (var i=0;i<mustLoad.length;i++)
{
var resType=mustLoad[i].type;
var resID=mustLoad[i].id;
if (!!Name.Sivory.Opensea.RBuilders[resType])
{
var resourceBuilder=Name.Sivory.Opensea.RBuilders[resType];
new resourceBuilder(game,resID);
}
else
{
throw "不支持的资源类型 ["+resType+"]";
}
}
var resLoadCount=0;
var handler=function(resource)
{
resLoadCount++;
var p={loaded:resLoadCount,total:instance.loadingQueue.length}
game.loader.process(p);//更新加载界面
if (resLoadCount==instance.loadingQueue.length)
{
callback();
}
}
for (var i=0;i<instance.loadingQueue.length;i++)
{
instance.loadingQueue[i].load(handler);
}
}
}
| JavaScript |
function OS_Interface(host,id)
{
this.$super=OS_Resource;
if (this.$super(host,id)===false) return;
delete this.$super;
this.show = function()
{
host.status.activeInterface = this;
}
this.refresh = function()
{
host.error("错误:执行了一个应该被重载的函数");
}
}
| JavaScript |
/**
* @fileOverview 游戏源类源文件
* @author <a href="http://sivory.my.phpcloud.com">Sivory</a>
* @version 0
*/
/**
* @class 游戏源类。对一个游戏实例中的数据与逻辑的托管单元,主要功能为向内核提供游戏执行时所需的数据与脚本。
* @author <a href="http://sivory.my.phpcloud.com">Sivory</a>
* @version 0
*/
Name.Sivory.Opensea.Source=function()
{
var instance=this; //引用当前实例
/**
* @private
* @field
* @description 被托管的XmlDocument对象
* @type
* @since 0.1
*/
this.dom=null
/**
* @public
* @function
* @description 根据给出的URL读取特定类型的XML文档,加载成功后执行回调函数。方法内部采用AJAX逻辑进行加载。
* @param {String} url XML资源的路径
* @param {String} type 服务器返回的具体资源类型,分“JSON”与“XML”。“XML”为纯XML文本格式;“JSON”为含有“data”域与“status”域的JSON格式文本,当其“status”域为1时,其“data”域须存放有XML文档。
* @param {Function} [callback] 加载完毕执行的回调函数
* @since 0.1
*/
this.load = function(url, type, callback)
{
var request=null;
/*
* 利用AJAX对象加载XML资源文件
* 若AJAX对象不存在则采用微软的ActiveX控件
*/
if(window.XMLHttpRequest){ // For Mozilla, Safari, Chrome, ...
request = new XMLHttpRequest();
} else if(window.Activexobject){ // For Internet Explorer
try {
request = new Activexobject("Msxml2.XMLHTTP");
} catch (e) {
try {
request = new Activexobject("Microsoft.XMLHTTP");
} catch (e) {
throw "在建立AJAX对象的时候发生异常(" + e + ")";
}
}
}
request.open("GET", url, true); //建立一个到url的GET异步请求
/*
* 在请求状态发生改变时执行托管函数
* 只有当状态为4,响应为200时才是成功
* 成功时需要取得XML文本,并将其转换为document对象
* 内部会用到{@link OS_Document#parse}函数帮助解析
*/
request.onreadystatechange = function(){
if (request.readyState == 4 && request.status == 200) //成功获得响应
{
//响应的XML文本
var xmlText = null;
//如果数据方式为xml,则取得其responseText字段作为XML文本
if (type.toLowerCase() == "xml")
{
xmlText = request.responseText;
} else if (type.toLowerCase() == "json")
{
try {
var response = eval("(" + request.responseText + ")");
} catch (e) {
throw "在解析请求的JSON数据时发生异常";
}
if (response.status == 1) //服务器成功找到数据并返回
{
xmlText = response.data;
}
else
{
throw "服务器未能返回所请求的数据";
}
}
//执行转换,将文本转换成为document对象
instance.parse(xmlText);
//调用回调函数
if (!!callback)
{
callback();
}
}
else if (request.readyState == 4 && request.status != 200)
{
throw "服务器返回错误代码";
}
}
request.send(); //发送请求
}
/**
* @public
* @description 将指定的字符串转换为文档对象,存放于当前实例中。
* @param {String} xmlString 存储有XML文档的字符串。
* @since 0.1
*/
this.parse=function(xmlString)
{
try {
if (!!window.DOMParser)
{
instance.dom = (new DOMParser).parseFromString(xmlString,"text/xml");
}
else if(!!window.ActiveXObject)
{
instance.dom = new ActiveXObject('Microsoft.XMLDOM');
instance.dom.async = false;
instance.dom.loadXml(xmlString);
}
} catch(e) {
throw "解析XML文档时发生错误:" + e;
}
if (instance.dom.childNodes[0].nodeName != "resource")
{
throw "XML文档格式不正确";
}
}
} | JavaScript |
/**
* @fileOverview Castle游戏实例类源文件
* @author <a href="http://sivory.my.phpcloud.com">Sivory</a>
* @version 0.0.1
*/
(function() {
/** @exports _Class as Name.Sivory.Castle.Core.Game */
var _Class =
/**
* @class Castle游戏实例类Game。它托管着一个游戏集成环境,保证游戏各部件的协同工作。游戏的主循环在此类中托管,另外,Game还负责游戏不同界面间的切换。
* @param {Name.Sivory.Castle.Core.Config} config 游戏实例配置参数对象,参见{@link Name.Sivory.Castle.Core.Config}
* @author <a href="http://sivory.my.phpcloud.com">Sivory</a>
* @version 0.0.1
*/
Name.Sivory.Castle.Core.Game = function(config) {
/**
* @public
* @field
* @constant
* @type String
* @description 游戏内核版本
* @since 0.0.1
*/
this.V = "0.0.1";
/**
* @public
* @field
* @type Name.Sivory.Castle.Core.Config
* @description 游戏内核配置对象
* @since 0.0.1
*/
this.config = new Name.Sivory.Castle.Core.Config();
/**
* @public
* @field
* @type Name.Sivory.Castle.Core.Stage
* @description 游戏渲染器
* @since 0.0.1
*/
this.stage = new Name.Sivory.Castle.Core.Stage(this);
/**
* @public
* @field
* @type Name.Sivory.Castle.Core.Studio
* @description 游戏音效管理器
* @since 0.0.1
*/
this.studio = new Name.Sivory.Castle.Core.Studio(this);
/**
* @public
* @field
* @type Name.Sivory.Castle.Core.Status
* @description 游戏状态机
* @since 0.0.1
*/
this.status = new Name.Sivory.Castle.Core.Status(this);
/**
* @public
* @field
* @type Name.Sivory.Castle.Core.Controller
* @description 游戏控制器
* @since 0.0.1
*/
this.controller = new Name.Sivory.Castle.Core.Controller(this);
/**
* @public
* @field
* @type Name.Sivory.Castle.Core.Source
* @description 游戏源码托管
* @since 0.0.1
*/
this.source = new Name.Sivory.Castle.Core.Source();
/**
* @public
* @field
* @type Name.Sivory.Castle.Core.Resource
* @description 游戏资源集合
* @since 0.0.1
*/
this.resource = new Name.Sivory.Castle.Core.Resource();
/**
* @public
* @field
* @type Name.Sivory.Castle.Core.Debug
* @description 游戏实例的调试单元
* @since 0.0.1
*/
this.debug = new Name.Sivory.Castle.Core.Debug(this);
/**
* @public
* @field
* @type Name.Sivory.Castle.Core.Loader
* @description 游戏加载数据的画面
* @since 0.0.1
*/
this.loader = new Name.Sivory.Castle.Core.Loader(this);
/**
* @public
* @field
* @type Number
* @description 游戏帧计数器
* @since 0.0.1
*/
this.frameCount = 0;
/**
* @public
* @field
* @type Number
* @description 游戏开始时间
* @since 0.0.1
*/
this.startTime = 0;
/**
* @private
* @field
* @type Object
* @description 内核运行前需要准备好的模块
* source 游戏源模块
* canvas 游戏渲染模块
* start 用户启动开关
* @since 0.0.1
*/
this.readyList = {
source: false,
canvas: false,
start: false
};
/**
* @public
* @field
* @type Name.Sivory.Castle.Util.Hook
* @description 主循环中循环体开始时将被执行的钩子
* @since 0.0.1
*/
this.frameBeginHook = new Name.Sivory.Castle.Util.Hook();
/**
* @public
* @field
* @type Name.Sivory.Castle.Util.Hook
* @description 主循环中循环体结束时将被执行的钩子
* @since 0.0.1
*/
this.frameEndHook = new Name.Sivory.Castle.Util.Hook();
/**
* @private
* @field
* @type Boolean
* @description 用于控制游戏主循环执行的开关
* @since 0.0.1
*/
this.loopStoped = true;
};
/**
* @public
* @function
* @description 启动游戏
* @since 0.0.1
*/
_Class.prototype.start = function() {
this.startTime = new Date().getTime();
this.ready("start");
};
/**
* @private
* @function
* @description 游戏内核初始化
* @since 0.0.1
*/
_CLass.prototype.init = function(config) {
//检测浏览器类型
this.checkAgent();
//构建游戏配置参数
this.config.combine(config);
var onXmlDone = function() {
this.ready("source");
};
//读取资源
this.source.load(this.config.resource, 'json', onXmlDone);
};
/**
* @private
* @function
* @description 检测浏览器的类型
* @since 0.0.1
*/
_Class.prototype.checkAgent = function() {
var agentString = navigator.userAgent.toLowerCase();
//先把Chrome挑出来,因为Chrome也有Safari的特征。
if(agentString.indexOf("chrome") > -1) {
this.userAgent = "C";
this.requestAnimationFrame = window.webkitRequestAnimationFrame;
} else if(agentString.indexOf("firefox") > -1) {
this.userAgent = "F";
this.requestAnimationFrame = window.mozRequestAnimationFrame;
} else if(agentString.indexOf("safari") > -1) {
this.userAgent = "S";
this.requestAnimationFrame = window.webkitRequestAnimationFrame;
} else if(agentString.indexOf("opera") > -1) {
this.userAgent = "O";
this.requestAnimationFrame = window.oRequestAnimationFrame;
} else if(agentString.indexOf("msie 9") > -1 || agentString.indexOf("msie 10") > -1) {
this.userAgent = "I";
this.requestAnimationFrame = window.msRequestAnimationFrame;
} else {
throw "Castle不支持当前浏览器";
};
};
/**
* @public
* @function
* @description 当游戏中的某个模块准备好时,调用此函数告知内核相应模块已准备好。
* @param {String} key 已准备好的模块的名称
* @since 0.0.1
*/
_Class.prototype.ready = function(key) {
if(this.readyList[key] === null || this.readyList[key] === undefined) return;
this.readyList[key] = true;
var allReady = true;
//检测全部模块是否都已就绪
for(index in this.readyList) {
allReady = allReady && this.readyList[index];
if(!allReady) break;
};
if(allReady) {
//新建一个入口界面
var entry = new OS_Menu(this, this.config.entryInterface);
this.loader.start();
entry.show();
OS_Resource.loadResource(this, this.loader, function() {
this.loader.stop();
entry.playBGM();
this.mainLoop();
});
};
};
/**
* @public
* @function
* @description 执行游戏的主循环
* @since 0.0.1
*/
_Class.prototype.runMainLoop=function()
{
//开启循环
this.loopStoped = false;
//执行游戏主循环
this.mainLoop();
}
/**
* @public
* @function
* @description 终止游戏的主循环
* @since 0.0.1
*/
_Class.prototype.stopMainLoop=function()
{
//停止循环
this.loopStoped=true;
}
/**
* @private
* @function
* @description 游戏主循环的循环体
* @since 0.0.1
*/
_Class.prototype.mainLoop = function() {
try {
this.frameCount++;
//执行循环体开始位置的钩子
this.frameBeginHook.run();
//开始记录循环体(帧)的调试信息
this.debug.start();
//更新处于活动状态中的界面
this.status.activeInterface.refresh();
//结束记录循环体(帧)的调试信息
this.debug.finish();
//执行循环体结束位置的钩子
this.frameEndHook.run();
//若主循环在正常执行,则请求执行主循环的下一个循环体
if(!loopStoped) {
this.requestAnimationFrame(mainLoop);
}
} catch(err) {
//停止主循环的执行
this.loopStoped = true;
//触发错误事件
if(typeof this.onError === "function") {
this.onError(err);
}
}
};
/**
* @private
* @function
* @description 安排一个动画级别的延迟执行循环体,此延迟一般由浏览器分配。
* @param {Function} func 循环体函数
* @since 0.0.1
*/
_Class.prototype.requestAnimationFrame = function(func) {
throw "Castle不支持当前浏览器";
};
/**
* @public
* @event
* @description 当游戏运行出错时触发此事件
* @param {Name.Sivory.Castle.Core.Game} game 游戏实例
* @param {String} err 错误信息
* @since 0.0.1
*/
_Class.prototype.onError = function(game, err) {
//do nothing...
};
})(); | JavaScript |
function OS_Frame(host,id)
{
this.$super=OS_Bitmap;
if (this.$super(host,id)===false) return;
delete this.$super;
this.load=function(handler)
{
this.loadBitmap();
this.loaded=true;
handler(this);
}
}
OS_Resource.Builder.put("frame",OS_Frame); | JavaScript |
/**
* @fileOverview 游戏资源基类源文件
* @author <a href="http://sivory.my.phpcloud.com">Sivory</a>
* @version 0
*/
/**
* @class 游戏资源基类,它是所有可被加载的游戏资源的祖先类
* @param {Name.Sivory.Opensea.Game} host 游戏实例
* @id {String} 资源索引
* @author <a href="http://sivory.my.phpcloud.com">Sivory</a>
* @version 0
*/
Name.Sivory.Opensea.Resource=function(host,id)
{
//建立游戏源的资源哈希表
if (host.resource.indexes==null)
{
host.resource.indexes={};
var resourcelist=OS_Resource.resourceDom.getElementsByTagName("resource")[0].childNodes;
for (var i=0;i<resourcelist.length;i++)
if (resourcelist[i].nodeType==1)
{
var key=resourcelist[i].getAttribute("id");
if (!!key) OS_Resource.indexes[key]=resourcelist[i];
}
}
//此资源若已存在,则什么都不做
if (host.resource.containsKey(id)) return false;
//为避免重复加载主角资源
if (host.status.leadingRole!=null && host.status.leadingRole.id==id) return false;
//将当前资源添加至资源管理器中
host.resource.put(id,this);
/**
* @public
* @field
* @desciption 资源的索引
* @since 0
*/
this.id=id;
this.resourceNode=OS_Resource.indexes[id];
if (this.resourceNode==null)
{
host.error("资源索引错误:"+id);
}
//遍历依赖项节点
if (this.resourceNode.getElementsByTagName("dependency").length>0)
{
var childNodes = this.resourceNode.getElementsByTagName("dependency")[0].getElementsByTagName("item");
for (var i=0;i<childNodes.length;i++)
{
var childNode = childNodes[i];
var resType = childNode.getAttribute("type");
var resID = childNode.childNodes[0].nodeValue;
if (OS_Resource.Builder.containsKey(resType))
{
var resourceBuilder=OS_Resource.Builder.get(resType);
new resourceBuilder(host,resID);
}
else
{
host.error("错误: 不支持的资源类型 ["+resType+"]");
}
}
}
this.loaded=false;
this.load = function(successHandler)
{
host.error("错误:执行了一个应该被重载的函数");
}
}
| JavaScript |
function OS_SceneActor(host,id)
{
this.$super=OS_Actor;
if (this.$super(host,id)===false) return;
delete this.$super;
this.load=function(handler)
{
this.loadActions();
this.loaded=true;
handler(this);
}
}
OS_Resource.Builder.put("sceneActor",OS_SceneActor);
| JavaScript |
function OS_Battler(host,id)
{
this.$super=OS_Resource;
if (this.$super(host,id)===false) return;
delete this.$super;
this.normalAttackSkill=null;
this.specialSkills=[];
this.load=function(handler)
{
var children=this.resourceNode.childNodes;
for (var i=0;i<children.length;i++)
{
if (children[i].nodeType!=1) continue;
var child=children[i];
switch(child.nodeName)
{
case "name":
this.name=child.childNodes[0].nodeValue;
break;
case "bild":
this.actor=OS_Resource.resource.get(child.childNodes[0].nodeValue);
break;
case "hp":
this.maxHp=Number(child.childNodes[0].nodeValue);
break;
case "mp":
this.maxMp=Number(child.childNodes[0].nodeValue);
break;
case "speed":
this.speed=Number(child.childNodes[0].nodeValue);
break;
case "attack":
this.attack=Number(child.childNodes[0].nodeValue);
break;
case "defense":
this.defense=Number(child.childNodes[0].nodeValue);
break;
case "magic":
this.magic=Number(child.childNodes[0].nodeValue);
break;
case "resistance":
this.resistance=Number(child.childNodes[0].nodeValue);
break;
case "experience":
this.experience=Number(child.childNodes[0].nodeValue);
break;
case "abilityGroup":
var abilityList=child.childNodes;
for (var j=0;j<abilityList.length;j++)
{
if (abilityList[j].nodeType!=1) continue;
var abilityNode=abilityList[j];
if (abilityNode.getAttribute("type")=="normalAttack")
{
this.normalAttackSkill=OS_Resource.resource.get(abilityNode.childNodes[0].nodeValue);
}
else
{
this.specialSkills.push(OS_Resource.resource.get(abilityNode.childNodes[0].nodeValue));
}
}
break;
}
}
this.loaded=true;
handler(this);
}
}
OS_Resource.Builder.put("battler",OS_Battler); | JavaScript |
function OS_Studio() {
var musicVolume = 100;
var soundVolume = 100;
var musicList=null;
var isRandom=false;
var currentIndex=0;
var musicCurrent=null;
var musicNext=null;
var len=0;
var os=this;
var changeTime=1000;
var stop=false;
this.setChangeTime=function(time){
changeTime=time;
}
this.getChangeTime=function(){
return changeTime;
}
this.playBGM = function(mList, isRdom) {
if(musicCurrent){
musicCurrent.stop();
}
musicList=mList;
len=musicList.length;
currentIndex=0;
musicCurrent=musicList[currentIndex];
musicCurrent.play();
isRandom=isRdom;
stop=false;
for(var index=0;index<len;index++){
musicList[index].setHandler("ended",this.playMusicList);
}
musicCurrent.play();
}
this.pauseBGM = function() {
stop=true;
var temp=(new Date()).getTime();
if (musicCurrent) {
var intervalID = window.setInterval(function() {
if ((new Date()).getTime()>=temp+changeTime) {
window.clearInterval(intervalID);
musicCurrent.pause();
return;
}
musicCurrent.setVolume(musicVolume*(1-((new Date()).getTime()-temp)/changeTime));
},
30);
}
}
this.stopBGM = function() {
stop=true;
var temp=(new Date()).getTime();
if (musicCurrent) {
var intervalID = window.setInterval(function() {
if ((new Date()).getTime()>=temp+changeTime) {
window.clearInterval(intervalID);
musicCurrent.stop();
return;
}
musicCurrent.setVolume(musicVolume*(1-((new Date()).getTime()-temp)/changeTime));
},
30);
}
}
this.resumeBGM = function() {
if (musicCurrent) {
musicCurrent.setVolume(0);
musicCurrent.play();
var intervalID = window.setInterval(function() {
if (musicCurrent.getVolume() >= musicVolume) {
window.clearInterval(intervalID);
return;
}
var temp = musicCurrent.getVolume() + 1;
musicCurrent.setVolume(temp);
},
30);
}
}
this.changeBGM = function(mList,isRdom) {
musicList=mList;
len=musicList.length;
currentIndex=0;
isRandom=isRdom;
for(var index=0;index<len;index++){
musicList[index].setHandler("ended",this.playMusicList);
}
musicNext=musicList[currentIndex];
musicNext.setVolume(0);
musicNext.play();
stop=false;
if(musicCurrent){
var temp=(new Date()).getTime();
var intervalID = window.setInterval(function() {
if ((new Date()).getTime()>=temp+changeTime) {
if(musicCurrent)
musicCurrent.stop();
if(musicNext){
musicNext.setVolume(musicVolume);
}
else{
musicNext=musicList[currentIndex];
musicNext.setVolume(musicVolume);
}
window.clearInterval(intervalID);
musicCurrent = musicNext;
musicNext = null;
return;
}
if(musicNext)
musicNext.setVolume(musicVolume*((new Date()).getTime()-temp)/changeTime);
if(musicCurrent)
musicCurrent.setVolume(musicVolume*(1-((new Date()).getTime()-temp)/changeTime));
},
30);
}
}
this.getMusicVolume = function() {
return musicVolume;
}
this.setMusicVolume = function(value) {
musicVolume = value;
}
this.getSoundVolume = function() {
return soundVolume;
}
this.setSoundVolume = function(value) {
soundVolume = value;
}
this.playSound = function(os_Sound) {
os_Sound.play();
}
this.playMusicList=function(){
if(stop==false){
if(isRandom){
currentIndex=Math.floor(Math.random()*len);
}
else{
if(currentIndex<len-1){
currentIndex=currentIndex+1;
}
else{
currentIndex=0;
}
}
musicCurrent=musicList[currentIndex];
musicCurrent.play();
}
}
}
| JavaScript |
function OS_Team(host,id)
{
this.$super=OS_Resource;
if (this.$super(host,id)===false) return;
delete this.$super;
this.members=[];
this.activeMemberIndex=0;
this.load=function(handler)
{
var children=this.resourceNode.childNodes;
for (var i=0;i<children.length;i++)
{
if (children[i].nodeType!=1) continue;
if (children[i].nodeName!="member") continue;
var child=children[i];
var member={};
var attributes=child.childNodes;
for (var j=0;j<attributes.length;j++)
{
if (attributes[j].nodeType!=1) continue;
var attribute=attributes[j];
var attributeValue=attribute.childNodes[0].nodeValue;
switch(attribute.nodeName)
{
case "name":
member.name=attributeValue;
break;
case "appearance":
member.appearance=eval("("+attributeValue+")");
break;
case "sceneActor":
member.sceneActor=OS_Resource.resource.get(attributeValue);
break;
case "battler":
member.battler=OS_Resource.resource.get(attributeValue);
break;
case "level":
member.maxlevel=100;
member.level=Number(attributeValue);
break;
case "initialExperience":
member.experience=0;
member.experienceLimit=Number(attributeValue);
break;
case "experienceAddition":
member.experienceAddition=Number(attributeValue);
break;
case "initialHp":
member.maxHp=Number(attributeValue);
member.hp=member.maxHp;
break;
case "hpAddition":
member.hpAddition=Number(attributeValue);
break;
case "initialMp":
member.maxMp=Number(attributeValue);
member.mp=member.maxMp;
break;
case "mpAddition":
member.mpAddition=Number(attributeValue);
break;
case "initialSpeed":
member.initialSpeed=Number(attributeValue);
break;
case "speedAddition":
member.speedAddition=Number(attributeValue);
break;
case "initialAttack":
member.initialAttack=Number(attributeValue);
break;
case "attackAddition":
member.attackAddition=Number(attributeValue);
break;
case "initialDefense":
member.initialDefense=Number(attributeValue);
break;
case "defenseAddition":
member.defenseAddition=Number(attributeValue);
break;
case "initialMagic":
member.initialMagic=Number(attributeValue);
break;
case "magicAddition":
member.magicAddition=Number(attributeValue);
break;
case "initialResistance":
member.initialResistance=Number(attributeValue);
break;
case "resistanceAddition":
member.resistanceAddition=Number(attributeValue);
break;
}
}
this.members.push(member);
if (!!member.appearance && this.activeMemberIndex==null)
{
this.activeMemberIndex=this.members.length-1;
}
}
if (host.status.team==null)
{
host.status.team=this;
}
this.loaded=true;
handler(this);
}
this.getActiveMember=function()
{
return this.members[this.activeMemberIndex];
}
this.nextActiveMember=function()
{
var index=this.activeMemberIndex+1;
while (index!=this.activeMemberIndex)
{
if (index==this.members.length) index=0;
if (!!this.members[index].appearance) break;
index++;
}
this.activeMemberIndex=index;
}
this.realNumber=function()
{
var res=0;
for (var i=0;i<this.members.length;i++)
{
if (!!this.members[i].appearance)
{
res++;
}
}
return res;
}
//入队
this.append=function(name)
{
for (var i=0;i<this.members.length;i++)
{
if (this.members[i].name==name)
{
this.members[i].appearance=true;
}
}
}
//离队
this.leave=function(name)
{
for (var i=0;i<this.members.length;i++)
{
if (this.members[i].name==name)
{
this.members[i].appearance=false;
}
}
}
var needSaveList=["appearance","level","maxHp","maxMp","experience","experienceLimit"];
this.encode=function()
{
var temp={};
for (var i=0;i<this.members.length;i++)
{
temp[this.members[i].name]={};
for (var j=0;j<needSaveList.length;j++)
{
temp[this.members[i].name][needSaveList[j]]=this.members[i][needSaveList[j]];
};
}
return JSON.stringify(temp);
}
this.decode=function(data)
{
var temp=eval("("+data+")");
for (var i=0;i<this.members.length;i++)
{
for (var j=0;j<needSaveList.length;j++)
{
this.members[i][needSaveList[j]]=temp[this.members[i].name][needSaveList[j]];
};
}
}
}
OS_Resource.Builder.put("team",OS_Team); | JavaScript |
/**
* @fileOverview Castle游戏运行配置参数类源文件
* @author <a href="http://sivory.my.phpcloud.com">Sivory</a>
* @version 0.0.1
*/
(function() {
/** @exports _Class as Name.Sivory.Castle.Core.Config */
var _Class =
/**
* @class Castle游戏运行配置参数类。主要功能是向游戏内核提供基本配置参数。由用户建立后传入Game类的构造函数,Game类构造函数可接受匿名创建的Config实例。
* @example new Name.Sivory.Castle.Core.Game({gameKey:"003332",width:800,height:600});
* @author <a href="http://sivory.my.phpcloud.com">Sivory</a>
* @version 0.0.1
* @see Name.Sivory.Castle.Core.Game
*/
Name.Sivory.Castle.Core.Config = function() {
//引用实例
var instance = this;
/**
* @public
* @field
* @type String
* @description 游戏容器的id,推荐使用div元素。Castle将在此元素中新建一个canvas元素。
* @default "open-sea-game"
* @since 0.0.1
*/
this.gameContainer = "open-sea-game";
/**
* @public
* @field
* @type String
* @description 游戏的资源文件路径。
* @default "../resource/resource.xml"
* @since 0.0.1
*/
this.resource = "../resource/resource.xml";
/**
* @public
* @field
* @type String
* @description 游戏资源的类型,可选为“xml”与“json”。当选择“xml”时,则要求资源返回数据必须是纯XML文本,当选择“json”时,则要求资源返回数据必须是{status:...,info:...,data:...}结构的JSON字符串。其中status可选0,1来表示请求是否成功。info值为若请求失败时失败的信息。data值为请求的XML文本。
* @default "xml"
* @since 0.0.1
*/
this.resourceType = "xml";
/**
* @public
* @field
* @type Number
* @description 游戏运行时的帧率,单位为frame/s
* @default 60
* @since 0.0.1
*/
this.fps = 60;
/**
* @public
* @field
* @type String
* @description 游戏入口界面id,可以是menu类资源id或是scene类资源id,此id须在XML文档中定义。
* @default "mainMenu"
* @since 0.0.1
*/
this.entryInterface = "mainMenu";
/**
* @public
* @field
* @type String
* @description 游戏入口界面的类型,目前可选menu、scene或是battle。
* @default "menu"
* @since 0.0.1
*/
this.entryInterfaceType = "menu";
/**
* @public
* @field
* @type Number
* @description 键盘按键延时。当玩家按住某个键不动时,将以此时间为间隔周期地触发按键事件。单位为毫秒。
* @default 500
* @since 0.0.1
*/
this.keyDelay = 500;
/**
* @public
* @field
* @type Number
* @description 游戏画布宽度。单位为像素。
* @default 600
* @since 0.0.1
*/
this.width = 600;
/**
* @public
* @field
* @type Number
* @description 游戏画布高度。单位为像素。
* @default 500
* @since 0.0.1
*/
this.height = 500;
/**
* @public
* @field
* @type Number
* @description 游戏单元格宽度。单位为像素。
* @default 32
* @since 0.0.1
*/
this.squarewidth = 32;
/**
* @public
* @field
* @type Number
* @description 游戏单元格高度。单位为像素。
* @default 32
* @since 0.0.1
*/
this.squareheight = 32;
/**
* @public
* @field
* @type Boolean
* @description 游戏调试模式开关。开启调试模式时,会在界面显示游戏数据。
* @default false
* @since 0.0.1
*/
this.debug = false;
/**
* @public
* @field
* @type String
* @description 游戏标识。用于游戏本地存储时区分不同游戏。原则上,一个游戏对应一个固定的游戏标识。取值为任意字符串。
* @default "default"
* @since 0.0.1
*/
this.gameKey = "default";
/**
* @public
* @field
* @type Array
* @description 游戏全局资源,即需要被优先加载的资源。格式参考默认值。
* @default [{id:"key-config",type:"keys"},{id:"initial-team",type:"team"}]
* @since 0.0.1
*/
this.mustLoad = [{
id: "key-config",
type: "keys"
}, {
id: "initial-team",
type: "team"
}];
};
/**
* @public
* @function
* @description 将另一个配置对象并入当前实例。
* @param {Name.Sivory.Castle.Config} config
* @since 0.0.1
*/
_Class.prototype.combine = function(config) {
if(!config) return;
for(key in instance)
if(config[key] != null && typeof config[key] != "function") instance[key] = config[key];
}
})(); | JavaScript |
function OS_Skill(host,id)
{
this.$super=OS_Resource;
if (this.$super(host,id)===false) return;
delete this.$super;
this.actions=[];
this.load=function(handler)
{
var children=this.resourceNode.childNodes;
for (var i=0;i<children.length;i++)
{
if (children[i].nodeType!=1) continue;
var child=children[i];
switch(child.nodeName)
{
case "name":
var childValue=child.childNodes[0].nodeValue;
this.name=childValue;
break;
case "selectTarget":
var childValue=child.childNodes[0].nodeValue;
this.selectTarget=childValue;
break;
case "selectCount":
var childValue=child.childNodes[0].nodeValue;
this.selectCount=childValue;
break;
case "cost":
var childValue=child.childNodes[0].nodeValue;
this.cost=childValue;
break;
case "actions":
var actionList=child.childNodes;
for (var j=0;j<actionList.length;j++)
{
if (actionList[j].nodeType!=1) continue;
var actionNode=actionList[j];
var action={name:actionNode.nodeName};
for (k=0;k<actionNode.attributes.length;k++)
{
action[actionNode.attributes[k].nodeName]=actionNode.attributes[k].nodeValue;
}
this.actions.push(action);
}
break;
}
}
this.loaded=true;
handler(this);
}
this.update=function(battle,source,target,starttime)
{
var nowTime=(new Date()).getTime();
var timeTemp=nowTime-starttime;
for (var i=0;i<this.actions.length;i++)
{
var action=this.actions[i];
switch(action.name)
{
case "walkForwardAction":
var duration=1500;
var fromPosition={x:source.position.x,y:source.position.y};
var toPosition={x:target[0].position.x,y:target[0].position.y};
if (target[0].faceto=="down")
{
toPosition.x-=32;
toPosition.y+=26;
}
else
{
toPosition.x+=32;
toPosition.y-=26;
}
if (timeTemp<duration)
{
source.currentPosition.x=fromPosition.x+(toPosition.x-fromPosition.x)*timeTemp/duration;
source.currentPosition.y=fromPosition.y+(toPosition.y-fromPosition.y)*timeTemp/duration;
var index=Math.floor(timeTemp/duration*12)%4+1;
var suffix="";
if (toPosition.y<fromPosition.y) suffix="b";
else suffix="f";
source.currentFrame=source.actor.actions["walk"+suffix+index];
return false;
}
else
{
source.currentPosition.x=toPosition.x;
source.currentPosition.y=toPosition.y;
timeTemp-=duration;
}
break;
case "walkBackAction":
var duration=1500;
var fromPosition={x:target[0].position.x,y:target[0].position.y};
var toPosition={x:source.position.x,y:source.position.y};
if (target[0].faceto=="down")
{
fromPosition.x-=32;
fromPosition.y+=26;
}
else
{
fromPosition.x+=32;
fromPosition.y-=26;
}
if (timeTemp<duration)
{
source.currentPosition.x=fromPosition.x+(toPosition.x-fromPosition.x)*timeTemp/duration;
source.currentPosition.y=fromPosition.y+(toPosition.y-fromPosition.y)*timeTemp/duration;
var index=Math.floor(timeTemp/duration*12)%4+1;
var suffix="";
if (toPosition.y<fromPosition.y) suffix="b";
else suffix="f";
source.currentFrame=source.actor.actions["walk"+suffix+index];
return false;
}
else
{
source.currentPosition.x=toPosition.x;
source.currentPosition.y=toPosition.y;
var suffix="";
if (source.faceto=="up") suffix="b";
else suffix="f";
source.currentFrame=source.actor.actions["stand"+suffix];
timeTemp-=duration;
}
break;
case "teleportForwardAction":
var duration=500;
var fromPosition={x:source.position.x,y:source.position.y};
var toPosition={x:target[0].position.x,y:target[0].position.y};
if (target[0].faceto=="down")
{
toPosition.x-=32;
toPosition.y+=26;
}
else
{
toPosition.x+=32;
toPosition.y-=26;
}
if (timeTemp<duration)
{
if (timeTemp<duration/2)
{
source.currentPosition.x=fromPosition.x;
source.currentPosition.y=fromPosition.y;
}
else
{
source.currentPosition.x=toPosition.x;
source.currentPosition.y=toPosition.y;
}
return false;
}
else
{
source.currentPosition.x=toPosition.x;
source.currentPosition.y=toPosition.y;
timeTemp-=duration;
}
break;
case "teleportBackAction":
var duration=1500;
var fromPosition={x:target[0].position.x,y:target[0].position.y};
var toPosition={x:source.position.x,y:source.position.y};
if (target[0].faceto=="down")
{
fromPosition.x-=32;
fromPosition.y+=26;
}
else
{
fromPosition.x+=32;
fromPosition.y-=26;
}
if (timeTemp<duration)
{
if (timeTemp<duration/2)
{
source.currentPosition.x=fromPosition.x;
source.currentPosition.y=fromPosition.y;
}
else
{
source.currentPosition.x=toPosition.x;
source.currentPosition.y=toPosition.y;
}
return false;
}
else
{
source.currentPosition.x=toPosition.x;
source.currentPosition.y=toPosition.y;
var suffix="";
if (source.faceto=="up") suffix="b";
else suffix="f";
source.currentFrame=source.actor.actions["stand"+suffix];
timeTemp-=duration;
}
break;
case "attackAction":
var duraion=1500;
if (timeTemp<duration)
{
var index=Math.floor(timeTemp/duration*6);
var suffix="";
if (target[0].faceto=="down") suffix="b";
else suffix="f";
if (index==0 || index==5)
{
source.currentFrame=source.actor.actions["stand"+suffix];
}
else
{
source.currentFrame=source.actor.actions["attack"+suffix+index];
}
if (target[0].faceto=="down") suffix="f";
else suffix="b";
if (index==3 || index==2)
{
target[0].currentFrame=target[0].actor.actions["hurt"+suffix];
}
return false;
}
else
{
var suffix="";
if (target[0].faceto=="down") suffix="f";
else suffix="b";
target[0].currentFrame=target[0].actor.actions["stand"+suffix];
timeTemp-=duration;
}
break;
case "healing":
for (var k=0;k<target.length;k++)
{
if (!target[k].hurtInfo)
{
var healthP=Number(action.healthPoint);
healthP+=source.magic;
healthP+=Math.floor(source.magic*Math.random());
target[k].hp+=healthP;
if (target[k].hp>target[k].maxHp)
{
healthP-=target[k].hp-target[k].maxHp;
target[k].hp=target[k].maxHp;
}
target[k].hurtInfo={damage:healthP,startTime:(new Date()).getTime(),type:"heal"};
}
}
break;
case "makeHurt":
for (var k=0;k<target.length;k++)
{
if (!target[k].hurtInfo)
{
damage=Number(action.baseDamage);
if (action.type=="physical")
{
damage+=source.attack;
damage+=Math.floor(source.attack*Math.random());
damage-=target[k].defense;
for(var m=0;m<target[k].states.length;m++)
{
if(target[k].states[m].test("defense"))
{
damage-=20;
break;
}
}
}
else if (action.type=="magic")
{
damage+=source.magic;
damage+=Math.floor(source.magic*Math.random());
damage-=target[k].resistance;
for(var m=0;m<target[k].states.length;m++)
{
if(target[k].states[m].test("defense"))
{
damage-=20;
break;
}
}
}
if (damage<0) damage=0;
target[k].hp-=damage;
if (target[k].hp<0) target[k].hp=0;
if (target[k].hp==0)
{
target[k].alive=false;
target[k].activePoint=0;
}
target[k].hurtInfo={damage:-damage,startTime:(new Date()).getTime(),type:"hurt"};
}
}
break;
case "makeState":
for(var k=0;k<target.length;k++)
{
if (!target[k].hurtInfo)
{
var state=new OS_BattlerState();
state.setName(action.state);
state.setNum(action.delay);
target[k].states.push(state);
var statesLabel={"chaos":"狂乱","sleep":"睡眠","block":"封印","defense":"防御"};
target[k].hurtInfo={damage:statesLabel[action.state],startTime:(new Date()).getTime(),type:"state"};
}
}
break;
case "playBattleEffect":
var effect=OS_Resource.resource.get(action.effect);
var duration=action.duration;
if (timeTemp<duration)
{
var position_temp=null;
var index=Math.floor(effect.length*timeTemp/duration);
if (action.position=="source")
{
position_temp=source;
var left=position_temp.currentPosition.x-effect.offset.x;
var top=position_temp.currentPosition.y-effect.offset.y;
battle.putEffect(effect.timeLine[index],left,top);
}
else
{
for (var k=0;k<target.length;k++)
{
position_temp=target[k];
var left=position_temp.currentPosition.x-effect.offset.x;
var top=position_temp.currentPosition.y-effect.offset.y;
battle.putEffect(effect.timeLine[index],left,top);
if (action.hurt=="true")
{
if (target[k].faceto=="down") suffix="f";
else suffix="b";
target[k].currentFrame=target[k].actor.actions["hurt"+suffix];
}
}
}
return false;
}
else
{
for (var k=0;k<target.length;k++)
{
if (target[k].faceto=="down") suffix="f";
else suffix="b";
if (action.hurt=="true")
{
target[k].currentFrame=target[k].actor.actions["stand"+suffix];
}
}
timeTemp-=duration;
}
break;
case "delay":
var duration=action.time;
if (timeTemp<duration)
{
return false;
}
else
{
timeTemp-=duration;
}
}
}
for (var i=0;i<target.length;i++)
{
delete target[i].hurtInfo;
}
//进行结算
return true;
}
}
OS_Resource.Builder.put("skill",OS_Skill); | JavaScript |
function OS_Stage(game)
{
var canvas=null;
var container=null;
var context=null;
var viewCenter={};
var initCanvas=function()
{
container=document.getElementById(game.config.gameContainer);
container.innerHtml="";
canvas=document.createElement("canvas");
canvas.width=game.config.width;
canvas.height=game.config.height;
container.appendChild(canvas);
context=canvas.getContext("2d");
game.ready("canvas");
}
window.addEventListener("load",initCanvas,false);
this.setViewCenter=function(x,y)
{
context.save();
//对于宽度边界小于屏幕宽度的情况,将中心视点置为地图X轴中心
if (game.status.activeInterface.world.colCount*game.config.squarewidth < game.config.width)
{
x=game.status.activeInterface.world.colCount*game.config.squarewidth/2;
}
else if (x<game.config.width/2)
{
x=game.config.width/2;
}
else if (x>game.status.activeInterface.world.colCount*game.config.squarewidth-game.config.width/2)
{
x=game.status.activeInterface.world.colCount*game.config.squarewidth-game.config.width/2;
}
//同理 将中心视点置于Y轴中心
if (game.status.activeInterface.world.rowCount*game.config.squareheight < game.config.height)
{
y=game.status.activeInterface.world.rowCount*game.config.squareheight/2;
}
else if (y<game.config.height/2)
{
y=game.config.height/2;
}
else if (y>game.status.activeInterface.world.rowCount*game.config.squareheight-game.config.height/2)
{
y=game.status.activeInterface.world.rowCount*game.config.squareheight-game.config.height/2;
}
viewCenter.x=x;
viewCenter.y=y;
context.translate(
game.config.width/2-x,
game.config.height/2-y
);
}
this.resetViewCenter=function()
{
context.restore();
}
this.drawSquare=function(color, left, top)
{
context.fillStyle=color;
context.fillRect(left,top,game.config.squarewidth,game.config.squareheight);
}
this.draw=function(bitmap, left, top, c)
{
var contextTemp=context;
if (!!c) contextTemp=c;
contextTemp.drawImage(
bitmap.source.getImage(),
bitmap.offsetx,
bitmap.offsety,
bitmap.width,
bitmap.height,
left,
top,
bitmap.width+0.5,
bitmap.height+0.5);
}
var box4=[[{},{}],[{},{}]];
box4[0][0].checks=[[-1,0],[0,-1],[-1,-1]];//4 2 1
box4[0][0].offsets=[{row:0,col:0},{row:0,col:0},{row:1,col:1},{row:1,col:1},{row:2,col:0},{row:2,col:0},{row:0,col:1},{row:2,col:1}];
box4[0][1].checks=[[-1,0],[0,1],[-1,1]];
box4[0][1].offsets=[{row:0,col:0},{row:0,col:0},{row:1,col:0},{row:1,col:0},{row:2,col:1},{row:2,col:1},{row:0,col:1},{row:2,col:0}];
box4[1][0].checks=[[1,0],[0,-1],[1,-1]];
box4[1][0].offsets=[{row:0,col:0},{row:0,col:0},{row:2,col:1},{row:2,col:1},{row:1,col:0},{row:1,col:0},{row:0,col:1},{row:1,col:1}];
box4[1][1].checks=[[1,0],[0,1],[1,1]];
box4[1][1].offsets=[{row:0,col:0},{row:0,col:0},{row:2,col:0},{row:2,col:0},{row:1,col:1},{row:1,col:1},{row:0,col:1},{row:1,col:0}];
this.fix=function(map,layer,row,col,c)
{
var contextTemp=context;
if (!!c) contextTemp=c;
var bitmap=map.mapdata[row][col][layer];
var left=game.config.squarewidth*col;
var top=game.config.squareheight*row;
var exlen=0.5;
var halfsw=game.config.squarewidth>>1;
var halfsh=game.config.squareheight>>1;
for (var ii=0;ii<2;ii++)
{
for (var jj=0;jj<2;jj++)
{
var res=0;
for (var i=0;i<3;i++)
{
var condition_row=row+box4[ii][jj].checks[i][0];
var condition_col=col+box4[ii][jj].checks[i][1];
if (condition_row<0 || condition_col<0 ||
condition_row>=map.rowCount || condition_col>=map.colCount ||
map.mapdata[condition_row][condition_col][layer]===bitmap)
{
var temp=4;
for (var j=0;j<i;j++) temp=temp>>1;
res+=temp;
}
}
var offset=box4[ii][jj].offsets[res];
contextTemp.drawImage(
bitmap.source.getImage(),
bitmap.offsetx+game.config.squarewidth*offset.col+jj*halfsw,
bitmap.offsety+game.config.squareheight*offset.row+ii*halfsh,
halfsw,
halfsh,
left+jj*halfsw,
top+ii*halfsh,
halfsw+exlen,
halfsh+exlen
);
}//for
}
}
this.drawWindow=function(win,left,top,width,height,flag)
{
win.drawSelf(context,left,top,width,height,flag);
}
this.getContext=function()
{
return context;
}
this.write=function(text, left, top)
{
if (!!text.background)
{
var paddingL=10;
var backH=22;
if (!!text.size) backH=Number(text.size)+10;
var backW=this.measureText(text).width;
context.fillStyle=text.background;
var backL=left-paddingL;
if (text.align=="right") backL=backL-backW;
if (text.align=="center") backL=backL-backW*0.5;
context.fillRect(backL,top,backW+paddingL*2,backH);
}
if (game.userAgent=="Firefox") top+=5;//浏览器兼容
context.fillStyle="#000";
if (!!text.color) context.fillStyle=text.color;
var perfix="";
if (text.bold===true) perfix="bold ";
context.shadowColor="transparent";
if (!!text.shadow)
{
context.shadowOffsetX=text.shadow.offsetX;
context.shadowOffsetY=text.shadow.offsetY;
context.shadowBlur=text.shadow.blur;
context.shadowColor=text.shadow.color;
}
var fontSize=12;
if (!!text.size) fontSize=text.size;
var fontFamily="Microsoft YaHei,sans-serif";
if (!!text.family) fontFamily=text.family;
context.font=perfix+fontSize+"px "+fontFamily;
context.textAlign="left";
if (!!text.align){context.textAlign=text.align;}
context.textBaseline="top";
if (!!text.baseLine){context.textBaseline=text.baseLine;}
if (!!text.maxWidth)
{
context.fillText(text.content, left, top, text.maxWidth);
}
else
{
context.fillText(text.content, left, top);
}
context.shadowColor="transparent";
}
this.measureText=function(text)
{
var perfix="";
if (text.bold===true) perfix="bold ";
var fontSize=12;
if (!!text.size) fontSize=text.size;
var fontFamily="Microsoft YaHei,sans-serif";
if (!!text.family) fontFamily=text.family;
context.font=perfix+fontSize+"px "+fontFamily;
return context.measureText(text.content);
}
this.fill=function(param)
{
if (param!=undefined)
{
//说明这是一个image资源
if (!!param.getImage)
{
var image=param.getImage();
var width=image.width;
var height=image.height;
height=height*game.config.width/width;
width=game.config.width;
if (height<game.config.height)
{
width=width*game.config.height/height;
height=game.config.height;
}
var left=game.config.width*0.5-width*0.5;
var top=game.config.height*0.5-height*0.5;
context.drawImage(image,0,0,image.width,image.height,left,top,width,height);
}
//这是一个字符串
else if (typeof param=="string")
{
context.fillStyle=param;
context.fillRect(0,0,game.config.width,game.config.height);
}
}
}
this.clear=function(param)
{
canvas.width=canvas.width;
this.fill(param);
}
}
| JavaScript |
function OS_SceneEffect(host,id)
{
this.$super=OS_Effect;
if (this.$super(host,id)===false) return;
delete this.$super;
this.load=function(handler)
{
this.loadTimestamps();
this.offset={
x:Number(this.resourceNode.getElementsByTagName("offset")[0].getElementsByTagName("x")[0].childNodes[0].nodeValue),
y:Number(this.resourceNode.getElementsByTagName("offset")[0].getElementsByTagName("y")[0].childNodes[0].nodeValue),
}
this.duration=Number(this.resourceNode.getElementsByTagName("duration")[0].childNodes[0].nodeValue);
this.layer=this.resourceNode.getElementsByTagName("layer")[0].childNodes[0].nodeValue;
this.loaded=true;
handler(this);
}
this.getFrame=function(time)
{
var index=Math.floor(time/this.duration*this.length);
if (index>=this.length) return false;
return this.timeLine[index];
}
}
OS_Resource.Builder.put("sceneEffect",OS_SceneEffect);
| JavaScript |
function OS_Sound(host,id)
{
this.$super=OS_Resource;
if (this.$super(host,id)===false) return;
delete this.$super;
var audio=new Audio();
audio.loop=false;
audio.preload=true;
audio.audoplay=false;
this.load=function(handler)
{
var instance=this;
audio.addEventListener("canplaythrough",function(){
instance.loaded=true;
handler(instance);
});
audio.src=this.resourceNode.getElementsByTagName("link")[0].textContent;
}
this.play=function(){
audio.play();
}
this.pause=function(){
audio.pause();
}
this.stop=function()
{
audio.pause();
audio.currentTime=0;
}
this.getVolume=function()
{
return Math.round(audio.volume*100);
}
this.setVolume=function(value)
{
if (value>100) value=100;
if (value<0) value=0;
audio.volume=value/100;
}
}
OS_Resource.Builder.put("sound",OS_Sound);
| JavaScript |
function OS_KeyConfig(host,id)
{
this.$super = OS_Resource;
if (this.$super(host,id)===false) return;
delete this.$super;
var keymap={};
this.load = function(handler)
{
var keys=this.resourceNode.getElementsByTagName("key");
for (var i=0;i<keys.length;i++)
{
var key=keys[i];
var value=key.getAttribute("value");
var keyCodes=key.getElementsByTagName("keyCode");
for (var j=0;j<keyCodes.length;j++)
{
var keyCode=keyCodes[j].childNodes[0].nodeValue;
keymap[keyCode]=value;
}
}
this.loaded=true;
handler(this);
}
this.keycode=function(code)
{
if (!keymap[code])
{
return keymap["default"];
}
else
{
return keymap[code];
}
}
host.control.keyConfig(this);
}
OS_Resource.Builder.put("keys",OS_KeyConfig); | JavaScript |
function OS_Battle(host,id)
{
this.$super=OS_Interface;
if (this.$super(host,id)===false) return;
delete this.$super;
var parent=null;
var background=null;
this.bgm=null;
var activeSkill=null;
var activeBattler=null;
var activeTarget=null;
var enemys=[];
var partners=[];
var step=null;
var stepStartTime=0;
var enemyPositions=[[340,160],[250,70],[500,190]];
var partnerPositions=[[150,320],[30,300],[230,400]];
var activeDialog=null;
var selectPointer=-1;
var selectSide=-1;
var effects=[]; //特效
var probability=0.6;
var victory=false;
var victoryTime;
var totalExperience;
this.putEffect=function(frame,left,top) //特效导入
{
effects.push({frame:frame,left:left,top:top});
}
var instance=this; //战斗实例
this.setActiveDialog=function(dialog) // 活动窗口
{
activeDialog=dialog;
}
this.load=function(handler) //初始化装载
{
var children=this.resourceNode.childNodes;
for (var i=0;i<children.length;i++)
{
if (children[i].nodeType!=1) continue;
var child=children[i];
switch(child.nodeName)
{
case "background":
var imageid=child.childNodes[0].nodeValue;
background=OS_Resource.resource.get(imageid);
break;
case "bgm":
var musicid=child.childNodes[0].nodeValue;
this.bgm=OS_Resource.resource.get(musicid);
break;
case "enemyGroup":
var enemyList=child.childNodes;
for (j=0;j<enemyList.length;j++)
{
if (enemyList[j].nodeType!=1) continue;
var enemyNode=enemyList[j];
var enemy={battler:OS_Resource.resource.get(enemyNode.childNodes[0].nodeValue)};
enemys.push(enemy);
}
break;
}
}
this.loaded=true;
handler(this);
}
this.changeStep=function(s) //移换步骤
{
step=s;
stepStartTime=(new Date()).getTime();
}
this.initEnemys=function() //初始化敌人队伍
{
var flag=0;
if (enemys.length==2) flag=1;
totalExperience=0;
for (var i=0;i<enemys.length;i++)
{
var enemy=enemys[i];
for (index in enemy.battler)
{
enemy[index]=enemy.battler[index];
}
enemy.hp=enemy.maxHp;
enemy.mp=enemy.maxMp;
enemy.currentFrame=enemy.actor.actions["standf"];
enemy.alive=true;
enemy.activePoint=0;
enemy.faceto="down";
enemy.careful=false;
enemy.borderSize=0;
enemy.borderLimit=68;
enemy.states=[];
enemy.side="enemy";
if (i<enemyPositions.length)
{
enemy.position={x:enemyPositions[i+flag][0],y:enemyPositions[i+flag][1]};
enemy.currentPosition={x:enemyPositions[i+flag][0],y:enemyPositions[i+flag][1]}
}
totalExperience+=enemy.experience;
}
}
this.initPartners=function() //初始化主角队伍
{
var flag=0;
var count=0;
victory=false;
if (host.status.team.realNumber()==2) flag=1;
partners=[];
for (var i=0;i<host.status.team.members.length;i++)
{
var member=host.status.team.members[i];
if (!member.appearance) continue;
var attrs=[
"speed","initialSpeed","speedAddition",
"attack","initialAttack","attackAddition",
"defense","initialDefense","defenseAddition",
"magic","initialMagic","magicAddition",
"resistance","initialResistance","resistanceAddition"
];
for (var j=0;j<attrs.length;j+=3)
{
member[attrs[j]]=member[attrs[j+1]]+(member.level-1)*member[attrs[j+2]];
}
member.actor=member.battler.actor;
member.currentFrame=member.actor.actions["standb"];
member.normalAttackSkill=member.battler.normalAttackSkill;
member.specialSkills=member.battler.specialSkills;
member.alive=true;
member.activePoint=0;
member.faceto="up";
member.careful=false;
member.borderSize=0;
member.borderLimit=68;
member.states=[];
member.mp=member.maxMp;
member.hp=member.maxHp;
member.upgrade=false;
member.side="partner";
if (count+flag<partnerPositions.length)
{
member.position={x:partnerPositions[count+flag][0],y:partnerPositions[count+flag][1]};
member.currentPosition={x:partnerPositions[count+flag][0],y:partnerPositions[count+flag][1]};
}
count++;
partners.push(member);
}
}
//更新各战斗角色的活动点数
this.updateActivePoint=function() //检测换谁攻击
{
for (var i=0;i<enemys.length;i++)
{
if (!enemys[i].alive) continue;
if (enemys[i].activePoint>=1000)
{
enemys[i].activePoint=-1;
activeBattler=enemys[i];
this.changeStep("chooseAction");
return;
}
}
for (var i=0;i<partners.length;i++)
{
if (!partners[i].alive) continue;
if (partners[i].activePoint>=1000)
{
partners[i].activePoint=-1;
activeBattler=partners[i];
this.changeStep("chooseAction");
return;
}
}
for (var i=0;i<enemys.length;i++)
{
if (!enemys[i].alive) continue;
enemys[i].activePoint+=enemys[i].speed*host.delayTime/100;
if (enemys[i].activePoint>1000) enemys[i].activePoint=1000;
}
for (var i=0;i<partners.length;i++)
{
if (!partners[i].alive) continue;
partners[i].activePoint+=partners[i].speed*host.delayTime/100;
if (partners[i].activePoint>1000) partners[i].activePoint=1000;
}
}
this.$show=this.show;
this.show=function()
{
parent=host.status.activeInterface; //活动主画面
this.$show();
host.studio.changeBGM([this.bgm]);
this.initEnemys();
this.initPartners();
this.changeStep("updateActivePoint");
}
this.over=function() //战斗结束
{
parent.resume();
host.status.activeInterface=parent;
host.studio.changeBGM([parent.bgm]);
if (!!this.callback) this.callback();
}
var getAliveEnemyIndex=function(isRandom) //敌人是否随机选择进行攻击
{
var aliveList=[];
for (var i=0;i<enemys.length;i++)
{
if (enemys[i].alive)
{
aliveList.push(i);
}
}
if (!!isRandom)
{
var index=Math.floor(Math.random()*aliveList.length);
return aliveList[index];
}
else if (aliveList.length>0)
{
return aliveList[0];
}
else
{
return false;
}
}
var getAlivePartnerIndex=function(isRandom) //主角是否随机选择进行攻击
{
var aliveList=[];
for (var i=0;i<partners.length;i++)
{
if (partners[i].alive)
{
aliveList.push(i);
}
}
if (!!isRandom)
{
var index=Math.floor(Math.random()*aliveList.length);
return aliveList[index];
}
else if (aliveList.length>0)
{
return aliveList[0];
}
else
{
return false;
}
}
var getAliveEnemys=function()
{
var aliveList=[];
for ( var i=0;i<enemys.length;i++)
{
if(enemys[i].alive)
{
aliveList.push(enemys[i]);
}
}
return aliveList;
}
var getAlivePartners=function()
{
var aliveList=[];
for(var i=0;i<partners.length;i++)
{
if(partners[i].alive)
{
aliveList.push(partners[i]);
}
}
return aliveList;
}
this.update=function()
{
switch(step)
{
case "updateActivePoint": //更新活动点数
var enemyAlive=getAliveEnemyIndex();
var partnerAlive=getAlivePartnerIndex();
if (enemyAlive===false)
{
this.changeStep("victory");
}
else if (partnerAlive===false)
{
this.changeStep("defeated");
}
else
{
this.updateActivePoint();
}
break;
case "chooseSkill": //选择技能
if (activeDialog==null)
{
var params={};
params.position="center";
params.width=180;
params.height=180;
params.text="技能";
params.key="$battleChooseSkill_val";
params.options=[];
for (var i=0;i<activeBattler.specialSkills.length;i++)
{
var skill=activeBattler.specialSkills[i];
var content={text:skill.name,value:i};
if(skill.cost>activeBattler.mp)
{
content={text:skill.name,value:i,disable:true};
}
params.options.push(content);
}
params.callback=function()
{
var actionChoosed=host.status.V.get(params.key);
activeSkill=activeBattler.specialSkills[actionChoosed];
var myside=0;
if (activeSkill.selectCount=="single")
{
selectPointer=getAliveEnemyIndex();
}
else
{
selectPointer="all";
}
if (activeSkill.selectTarget=="enemy")
{
selectSide=1-myside;
}
else
{
selectSide=myside;
}
instance.changeStep("chooseTargetToUseSkill");
}
activeDialog=new OS_SelectDialog(host,this,parent.getWinRes(),params);
activeDialog.open();
}
else
{
if (!!host.status.checkKeyPressed("esc"))
{
activeDialog.setCallback(function(){
instance.changeStep("chooseAction");
});
activeDialog.close();
}
else
{
activeDialog.interceptKey();
activeDialog.update();
}
}
break;
case "chooseTargetToUseSkill": //选择目标使用技能
if (activeBattler.side=="partner")
{
var selectCount=partners.length;
if (selectSide==1) selectCount=enemys.length;
var upKey=host.status.checkKeyPressed("up");
var leftKey=host.status.checkKeyPressed("left");
var downKey=host.status.checkKeyPressed("down");
var rightKey=host.status.checkKeyPressed("right");
var enterKey=host.status.checkKeyPressed("enter");
var escKey=host.status.checkKeyPressed("esc");
var spaceKey=host.status.checkKeyPressed("space");
if (!!enterKey || !!spaceKey)
{
activeBattler.activePoint=0;
if (selectPointer!="all")
{
activeTarget=[selectSide==0?partners[selectPointer]:enemys[selectPointer]];
}
else
{
if (selectSide==1) activeTarget=getAliveEnemys();
else activeTarget=getAlivePartners();
}
selectPointer=-1;
selectSide=-1;
activeBattler.mp-=activeSkill.cost;
this.changeStep("updateSkill");
}
else if (!!escKey)
{
selectPointer=-1;
selectSide=-1;
this.changeStep("chooseSkill");
}
else if (selectPointer=="all")
{}
else if (!!upKey || !!leftKey)
{
var targetsTemp=selectSide==0?partners:enemys;
do{
selectPointer=(selectPointer-1+selectCount)%selectCount;
}while(!targetsTemp[selectPointer].alive);
}
else if (!!downKey || !!rightKey)
{
var targetsTemp=selectSide==0?partners:enemys;
do{
selectPointer=(selectPointer+1)%selectCount;
}while(!targetsTemp[selectPointer].alive);
}
var stateList=activeBattler.states;
var len=stateList.length;
var count=0;
var index=0;
while(count<len)
{
stateList[index].setNum(stateList[index].getNum()-1);
if(stateList[index].getNum()==0)
{
stateList.splice(index,1);
}
else
{
index++;
}
count++;
}
}
else //怪物使用技能
{
activeSkill=activeBattler.specialSkills[Math.floor(Math.random()*activeBattler.specialSkills.length)];
if(!activeSkill)
{
this.changeStep("chooseTargetToAttack");
break;
}
activeBattler.activePoint=0;
var stateList=activeBattler.states;
var state=null;
for(var i=0;i<stateList.length;i++) //判断是否有混沌状态
{
if(stateList[i].test("chaos"))
{
state="chaos";
break;
}
}
if(!!state)
{
if(activeSkill.selectCount=="single")
{
var indexRandom=getAliveEnemyIndex(true);
activeTarget=[enemys[indexRandom]];
}
else
{
activeTarget=getAliveEnemys();
}
}
else
{
if(activeSkill.selectCount=="single")
{
var indexRandom=getAlivePartnerIndex(true);
activeTarget=[partners[indexRandom]];
}
else
{
activeTarget=getAlivePartners();
}
}
stateList=activeBattler.states;
var len=stateList.length;
var count=0;
var index=0;
while(count<len)
{
stateList[index].setNum(stateList[index].getNum()-1);
if(stateList[index].getNum()==0)
{
stateList.splice(index,1);
}
else
{
index++;
}
count++;
}
this.changeStep("updateSkill");
}
break;
case "chooseAction": //选择方法
if (activeBattler.side=="partner")
{
var state=null;
var stateList=activeBattler.states;
for(var i=0;i<stateList.length;i++) //判断是否有睡眠状态
{
if(stateList[i].test("sleep"))
{
state="sleep";
break;
}
}
if(!!state)
{
stateList=activeBattler.states;
var len=stateList.length;
var count=0;
var index=0;
while(count<len)
{
stateList[index].setNum(stateList[index].getNum()-1);
if(stateList[index].getNum()==0)
{
stateList.splice(index,1);
}
else
{
index++;
}
count++;
}
activeBattler.activePoint=0;
this.changeStep("updateActivePoint");
break;
}
for(var i=0;i<stateList.length;i++) //判断是否有混沌状态
{
if(stateList[i].test("chaos"))
{
state="chaos";
break;
}
}
if(!!state)
{
this.changeStep("chooseTargetToAttack");
break;
}
if (activeDialog==null)
{
for(var i=0;i<stateList.length;i++) //判断是否有封锁技能状态
{
if(stateList[i].test("block"))
{
state="block";
break;
}
}
var params={};
params.position="center";
params.width=140;
params.height=150;
params.text=activeBattler.name;
params.key="$battleChooseAction_val";
if(!state)
{
params.options=[{text:" 攻击 ",value:"攻击"},{text:" 技能 ",value:"技能"},{text:" 防御 ",value:"防御"}]; }
else
{
params.options=[{text:" 攻击 ",value:"攻击"},{text:" 技能 ",value:"技能",disable:true},{text:" 防御 ",value:"防御"}];
}
params.callback=function()
{
var actionChoosed=host.status.V.get(params.key);
switch(actionChoosed)
{
case "攻击":
activeSkill=activeBattler.normalAttackSkill;
var myside=0;
if (activeSkill.selectCount=="single")
{
selectPointer=getAliveEnemyIndex();
}
else
{
selectPointer="all";
}
if (activeSkill.selectTarget=="enemy")
{
selectSide=1-myside;
}
else
{
selectSide=myside;
}
instance.changeStep("chooseTargetToAttack");
break;
case "技能":
instance.changeStep("chooseSkill");
break;
case "防御":
stateList=activeBattler.states;
var len=stateList.length;
var count=0;
var index=0;
while(count<len)
{
stateList[index].setNum(stateList[index].getNum()-1);
if(stateList[index].getNum()==0)
{
stateList.splice(index,1);
}
else
{
index++;
}
count++;
}
var state=new OS_BattlerState();
state.setName("defense");
state.setNum(1);
activeBattler.states.push(state);
activeBattler.activePoint=200;
instance.changeStep("updateActivePoint");
break;
}
}
activeDialog=new OS_SelectDialog(host,this,parent.getWinRes(),params);
activeDialog.open();
}
else
{
activeDialog.interceptKey();
activeDialog.update();
}
}
//怪物进攻
else
{
var ranNum=Math.floor(Math.random()*10);
var state=null;
var stateList=activeBattler.states;
for(var i=0;i<stateList.length;i++) //判断是否有睡眠状态
{
if(stateList[i].test("sleep"))
{
state="sleep";
break;
}
}
if(!!state)
{
stateList=activeBattler.states;
var len=stateList.length;
var count=0;
var index=0;
while(count<len)
{
stateList[index].setNum(stateList[index].getNum()-1);
if(stateList[index].getNum()==0)
{
stateList.splice(index,1);
}
else
{
index++;
}
count++;
}
activeBattler.activePoint=0;
this.changeStep("updateActivePoint");
break;
}
for(var i=0;i<stateList.length;i++) //判断是否有封锁技能状态
{
if(stateList[i].test("block"))
{
state="block";
break;
}
}
if(ranNum<10*probability&&!state)
{
this.changeStep("chooseTargetToUseSkill");
}
else
{
this.changeStep("chooseTargetToAttack");
}
}
break;
case "chooseTargetToAttack": //选择目标进行攻击
if (activeBattler.side=="partner")
{
var state=null;
var stateList=activeBattler.states;
activeSkill=activeBattler.normalAttackSkill;
for(var i=0;i<stateList.length;i++) //判断是否有混沌状态
{
if(stateList[i].test("chaos"))
{
state="chaos";
break;
}
}
if(!!state)
{
stateList=activeBattler.states;
var len=stateList.length;
var count=0;
var index=0;
while(count<len)
{
stateList[index].setNum(stateList[index].getNum()-1);
if(stateList[index].getNum()==0)
{
stateList.splice(index,1);
}
else
{
index++;
}
count++;
}
var indexRandom=getAlivePartnerIndex(true);
activeTarget=[partners[indexRandom]];
this.changeStep("updateSkill");
break;
}
var selectCount=partners.length;
if (selectSide==1) selectCount=enemys.length;
var upKey=host.status.checkKeyPressed("up");
var leftKey=host.status.checkKeyPressed("left");
var downKey=host.status.checkKeyPressed("down");
var rightKey=host.status.checkKeyPressed("right");
var enterKey=host.status.checkKeyPressed("enter");
var escKey=host.status.checkKeyPressed("esc");
var spaceKey=host.status.checkKeyPressed("space");
if (!!enterKey || !!spaceKey)
{
activeBattler.activePoint=0;
if (selectPointer!="all")
{
activeTarget=[selectSide==0?partners[selectPointer]:enemys[selectPointer]];
}
else
{
if (selectSide==1) activeTarget=enemys;
else activeTarget=partners;
}
selectPointer=-1;
selectSide=-1;
this.changeStep("updateSkill");
}
else if (!!escKey)
{
selectPointer=-1;
selectSide=-1;
this.changeStep("chooseAction");
}
else if (selectPointer=="all")
{}
else if (!!upKey || !!leftKey)
{
do{
selectPointer=(selectPointer-1+selectCount)%selectCount;
}while(!enemys[selectPointer].alive);
}
else if (!!downKey || !!rightKey)
{
do{
selectPointer=(selectPointer+1+selectCount)%selectCount;
}while(!enemys[selectPointer].alive);
}
stateList=activeBattler.states;
var len=stateList.length;
var count=0;
var index=0;
while(count<len)
{
stateList[index].setNum(stateList[index].getNum()-1);
if(stateList[index].getNum()==0)
{
stateList.splice(index,1);
}
else
{
index++;
}
count++;
}
}
else //攻击方为怪物
{
activeBattler.activePoint=0;
activeSkill=activeBattler.normalAttackSkill;
var stateList=activeBattler.states;
var state=null;
for(var i=0;i<stateList.length;i++) //判断是否有混沌状态
{
if(stateList[i].test("chaos"))
{
state="chaos";
break;
}
}
if(!!state)
{
var indexRandom=getAliveEnemyIndex(true);
activeTarget=[enemys[indexRandom]];
this.changeStep("updateSkill");
}
else
{
var indexRandom=getAlivePartnerIndex(true);
activeTarget=[partners[indexRandom]];
this.changeStep("updateSkill");
}
stateList=activeBattler.states;
var len=stateList.length;
var count=0;
var index=0;
while(count<len)
{
stateList[index].setNum(stateList[index].getNum()-1);
if(stateList[index].getNum()==0)
{
stateList.splice(index,1);
}
else
{
index++;
}
count++;
}
}
break;
case "updateSkill": //更新技能动画
var finish=activeSkill.update(this,activeBattler,activeTarget,stepStartTime);
if (!!finish)
{
this.changeStep("updateActivePoint");
activeSkill=null;
activeTarget=null;
}
break;
case "victory":
if(!victory) //防止多次计算
{
for(var k=0;k<partners.length;k++)
{
partners[k].experience+=totalExperience;
while(partners[k].experience>=partners[k].experienceLimit)
{
partners[k].experienceLimit*=partners[k].experienceAddition;
if(partners[k].level<partners[k].maxlevel)
{
partners[k].level+=1;
partners[k].upgrade=true;
partners[k].maxHp+=partners[k].hpAddition;
partners[k].hp=partners[k].maxHp;
partners[k].maxMp+=partners[k].mpAddition;
partners[k].mp=partners[k].maxMp;
}
}
}
victoryTime=(new Date()).getTime();
victory=true;
}
for (var i=0;i<partners.length;i++)
{
partners[i].currentFrame=partners[i].actor.actions["victory"];
if (!partners[i].alive)
{
partners[i].hp=1;
partners[i].alive=true;
}
}
if (
host.status.checkKeyPressed("esc")||
host.status.checkKeyPressed("enter")||
host.status.checkKeyPressed("space")||
(new Date()).getTime()-stepStartTime>5000
)
{
host.status.V.put("$OutcomeOfTheBattle","victory");
this.over();
}
break;
case "defeated":
for (var i=0;i<partners.length;i++)
{
if (!partners[i].alive)
{
partners[i].hp=1;
}
}
for (var i=0;i<enemys.length;i++)
{
enemys[i].currentFrame=enemys[i].actor.actions["victory"];
}
if (
host.status.checkKeyPressed("esc")||
host.status.checkKeyPressed("enter")||
host.status.checkKeyPressed("space")||
(new Date()).getTime()-stepStartTime>5000
)
{
host.status.V.put("$OutcomeOfTheBattle","defeated");
this.over();
}
break;
}
}
this.drawBattler=function(battler) //绘制怪物
{
if (!battler.alive)
{
var suffix="";
if (battler.faceto=="down") suffix="f";
else suffix="b";
battler.currentFrame=battler.actor.actions["dead"+suffix];
}
var action=null;
var barWidth=64;
var barTop=100;
var drawBar=false;
if (!battler.position) return;
var duration=1000;
var nowTime=(new Date()).getTime();
var alpha=Math.sin(Math.PI*(nowTime%duration/duration))*1;
if (battler==activeBattler && activeTarget!=null)
{}
else
{
var myside=0;
if (battler.side=="enemy") myside=1;
if (selectSide==0 && partners[selectPointer]==battler || selectSide==1 && enemys[selectPointer]==battler || selectSide==myside && selectPointer=="all" && battler.alive)
{
battler.borderSize+=host.delayTime/100*64;
if (battler.borderSize>battler.borderLimit) battler.borderSize=battler.borderLimit;
}
else
{
battler.borderSize-=host.delayTime/100*64;
if (battler.borderSize<0) battler.borderSize=0;
}
drawBar=true;
}
host.stage.draw(battler.currentFrame,battler.currentPosition.x,battler.currentPosition.y);
if (drawBar && battler.alive)
{
//画血条
host.stage.getContext().fillStyle="rgba(255,255,255,0.6)";
host.stage.getContext().fillRect(battler.currentPosition.x+(128-barWidth)/2,battler.currentPosition.y+barTop,barWidth,3);
host.stage.getContext().fillStyle="rgba(255,0,0,1)";
var hpwidth=barWidth*battler.hp/battler.maxHp;
host.stage.getContext().fillRect(battler.currentPosition.x+(128-barWidth)/2,battler.currentPosition.y+barTop,hpwidth,3);
//画法条
host.stage.getContext().fillStyle="rgba(255,255,255,0.6)";
host.stage.getContext().fillRect(battler.currentPosition.x+(128-barWidth)/2,battler.currentPosition.y+barTop+5,barWidth,3);
host.stage.getContext().fillStyle="rgba(63,72,255,1)";
var hpwidth=barWidth*battler.mp/battler.maxMp;
host.stage.getContext().fillRect(battler.currentPosition.x+(128-barWidth)/2,battler.currentPosition.y+barTop+5,hpwidth,3);
//画动作条
if (battler.activePoint>-1)
{
host.stage.getContext().fillStyle="rgba(255,255,255,1)";
var hpwidth=barWidth*battler.activePoint/1000;
}
else
{
host.stage.getContext().fillStyle="rgba(255,255,255,"+alpha+")";
var hpwidth=barWidth;
}
host.stage.getContext().fillRect(battler.currentPosition.x+(128-barWidth)/2,battler.currentPosition.y+barTop+10,hpwidth,3);
//画状态
var statesLabel={"chaos":"乱","sleep":"眠","block":"封","defense":"防"};
for (var i=0;i<battler.states.length;i++)
{
var left=battler.currentPosition.x+40+i*17;
var top=battler.currentPosition.y+barTop+12;
host.stage.write({
content:statesLabel[battler.states[i].getName()],
align:"center",
color:"#fff",
size:14,
bold:false,
shadow:{offsetX:1,offsetY:1,blur:1,color:"#333"}},left,top);
}
}
//画选择框
if (battler.borderSize>0)
{
var border_left=battler.currentPosition.x+64-battler.borderSize*0.5;
var border_top=battler.currentPosition.y+64-battler.borderSize*0.5;
host.stage.getContext().lineWidth=2.0;
host.stage.getContext().strokeStyle="rgba(255,255,255,"+(alpha*0.8+0.2)+")";
host.stage.getContext().strokeRect(border_left,border_top,battler.borderSize,battler.borderSize);
var name_left=battler.currentPosition.x+64;
var name_top=battler.currentPosition.y+6;
host.stage.write({content:battler.name,color:"#fff",size:16,align:"center",bold:true,shadow:{offsetX:1,offsetY:1,blur:1,color:"#333"}},name_left,name_top);
}
//画附加信息
if (!!battler.hurtInfo)
{
var timeTemp=((new Date()).getTime()-battler.hurtInfo.startTime);
var duration=1000;
var left=battler.currentPosition.x+64;
var top=battler.currentPosition.y-timeTemp/duration*50+32;
var alpha=1-timeTemp/duration;
var damage=battler.hurtInfo.damage;
if (battler.hurtInfo.type=="hurt")
{
var damageColor="rgba(255,0,0,"+alpha+")";
}
if (battler.hurtInfo.type=="heal")
{
var damageColor="rgba(0,255,0,"+alpha+")";
}
if (battler.hurtInfo.type=="state")
{
var damageColor="rgba(255,228,0,"+alpha+")";
}
if (alpha>0)
{
host.stage.write({content:damage,align:"center",color:damageColor,size:20,bold:true},left,top);
}
}
if (step=="victory")
{
host.stage.write({
content:"战斗胜利!",
align:"center",
baseLine:"middle",
color:"#fff",
bold:true,
shadow:{offsetX:1,offsetY:1,blur:1,color:"#333"},
size:48},
host.config.width*0.5,host.config.height*0.5);
if(victory&&battler.side=="partner")
{
var timeTemp=((new Date()).getTime()-victoryTime);
var duration=2000;
var left=battler.currentPosition.x+64;
var top=battler.currentPosition.y-timeTemp/duration*50+32;
var alpha=1-timeTemp/duration;
if (alpha>0)
{
host.stage.write({content:"获得"+totalExperience+"点经验值"+(battler.upgrade?" 升级了!":"")
,align:"center",color:"rgba(255,255,255,"+alpha+")",size:20,bold:true},left,top);
}
}
}
if (step=="defeated")
{
host.stage.write({
content:"战斗失败!",
align:"center",
baseLine:"middle",
color:"#fff",
bold:true,
shadow:{offsetX:1,offsetY:1,blur:1,color:"#333"},
size:48},
host.config.width*0.5,host.config.height*0.5);
}
}
this.drawEffect=function() //绘制特效
{
for (var i=0;i<effects.length;i++)
{
host.stage.draw(effects[i].frame,effects[i].left,effects[i].top);
}
}
this.refresh=function()
{
effects.splice(0); //清空
this.update();
host.stage.clear(background);
for (var i=0;i<enemys.length;i++)
{
this.drawBattler(enemys[i]);
}
for (var i=0;i<partners.length;i++)
{
this.drawBattler(partners[i]);
}
this.drawEffect();
if (activeDialog!=null)
{
activeDialog.drawSelf();
}
}
}
OS_Resource.Builder.put("battle",OS_Battle); | JavaScript |
function OS_Loader(game)
{
var angles=[
0,
Math.PI*0.1,
Math.PI*0.2,
Math.PI*0.3,
Math.PI*-0.1,
Math.PI*-0.2,
Math.PI*-0.3,
];
var intervalID=null;
var total=1;
var loaded=0;
var getProcessWidth=function()
{
return 420*loaded/total;
}
var drawPoint=function(context,r,angle,len)
{
context.save();
context.translate(game.config.width*0.5,game.config.height*0.5);
context.rotate(angle);
context.beginPath();
context.arc(0,len,r,0,Math.PI*2,true);
context.fill();
context.restore();
}
var frame=function()
{
var context=game.stage.getContext();
context.fillStyle="rgba(255,255,255,1)";
context.fillRect(0,0,game.config.width,game.config.height);
for (var i=0;i<angles.length;i++)
{
var e=Math.abs(Math.sin((angles[i]+Math.PI)/2))*0.1+Math.PI*0.01;
angles[i]+=e;
if (i<angles.length-1 && angles[i+1]-angles[i]<Math.PI*0.1) angles[i]=angles[i+1]-Math.PI*0.1;
context.fillStyle="rgba(70,70,70,"+(Math.sin((angles[i])/4)>0?Math.sin((angles[i])/4):0)+")";
drawPoint(context,4,angles[i],40);
if (Math.sin((angles[i])/4)<-0.8){angles[i]+=Math.PI;}
}
context.fillStyle="rgba(210,210,210,1)";
context.fillRect(game.config.width*0.5-210,game.config.height*0.5+150,getProcessWidth(),20);
context.strokeStyle="rgba(190,190,190,1)";
context.lineWidth=2;
context.strokeRect(game.config.width*0.5-210,game.config.height*0.5+150,420,20);
game.stage.write({content:"Loading",align:"center",size:20,color:"rgba(70,70,70,1)",bold:true},game.config.width*0.5,game.config.height*0.5+80);
game.stage.write({content:"Powered By MovingCastle©",align:"right",baseline:"bottom",size:12,color:"rgba(60,60,60,1)"},game.config.width-20,game.config.height-30);
}
this.start=function()
{
//angle1=Math.random()*Math.PI*2;
//angle2=Math.random()*Math.PI*2;
//angle3=Math.random()*Math.PI*2;
//angle4=Math.random()*Math.PI*2;
//game.stage.clear("#fff");
intervalID=window.setInterval(frame,20);
lastProcessTime=(new Date()).getTime();
}
this.process=function(p)
{
loaded=p.loaded;
total=p.total;
}
this.stop=function()
{
window.clearInterval(intervalID);
game.stage.clear("#fff");
}
}
| JavaScript |
function OS_Condition(host,active,node)
{
this.check=function()
{
host.error("未被重载的抽象函数");
}
}
OS_Condition.list=new OS_HashTable();
//取得一类效验器
OS_Condition.getInstance=function(host,active,node)
{
var tagname=node.nodeName;
if (!OS_Condition.list.containsKey(tagname)) return null;
var condition=OS_Condition.list.get(tagname);
return new condition(host,active,node);
}
| JavaScript |
/**
* @fileOverview Contains standard code in the namespace 'wbos' and code specifically written for Codeview in the namespace 'codeview'
* @author Wouter Bos (www.thebrightlines.com)
* @since 1.0 - 2010-09-10
* @version 1.0 - 2010-09-10
*/
if (typeof(wbos) == "undefined") {
/**
* @namespace Standard code of Wouter Bos (wbos)
*/
wbos = {}
}
if (typeof(wbos.CssTools) == "undefined") {
/**
* @namespace Namespace for CSS-related functionality
*/
wbos.CssTools = {}
}
/**
* @namespace Fallback for CSS advanced media query
* @class
* @since 1.0 - 2010-09-10
* @version 1.0 - 2010-09-10
*/
wbos.CssTools.MediaQueryFallBack = ( function() {
var config = {
cssScreen: "/css/screen.css",
cssHandheld: "/css/handheld.css",
mobileMaxWidth: 660,
testDivClass: "cssLoadCheck",
dynamicCssLinkId: "DynCssLink",
resizeDelay: 30
}
var noMediaQuery = false;
var delay;
var currentCssMediaType;
// Adding events to elements in the DOM without overwriting it
function addEvent(element, newFunction, eventType) {
var oldEvent = eval("element." + eventType);
var eventContentType = eval("typeof element." + eventType)
if ( eventContentType != 'function' ) {
eval("element." + eventType + " = newFunction")
} else {
eval("element." + eventType + " = function(e) { oldEvent(e); newFunction(e); }")
}
}
// Get the the inner width of the browser window
function getWindowWidth() {
if (window.innerWidth) {
return window.innerWidth;
} else if (document.documentElement.clientWidth) {
return document.documentElement.clientWidth;
} else if (document.body.clientWidth) {
return document.body.clientWidth;
} else{
return 0;
}
}
function addCssLink(cssHref) {
var cssNode = document.createElement('link');
var windowWidth;
cssNode.type = 'text/css';
cssNode.rel = 'stylesheet';
cssNode.media = 'screen, handheld, fallback';
cssNode.href = cssHref;
document.getElementsByTagName("head")[0].appendChild(cssNode);
}
/* Start public */
return {
/**
* Adds link to CSS in the head if no CSS is loaded
*
* @since 1.0 - 2010-08-21
* @version 1.0 - 2010-08-21
* @param {String|Object} cssScreen URL to CSS file for larger screens
* @param {String|Object} cssHandheld URL to CSS file for smaller screens
* @param {Number} mobileMaxWidth Maximum width for handheld devices
* @example
* wbos.CssTools.MediaQueryFallBack.LoadCss(['screen.css', 'screen2.css'], 'mobile.css', 480)
*/
LoadCss: function(cssScreen, cssHandheld, mobileMaxWidth) {
// Set config values
if (typeof(cssScreen) != "undefined") {
config.cssScreen = cssScreen;
}
if (typeof(cssHandheld) != "undefined") {
config.cssHandheld = cssHandheld;
}
if (typeof(mobileMaxWidth) != "undefined") {
config.mobileMaxWidth = mobileMaxWidth;
}
// Check if CSS is loaded
var cssloadCheckNode = document.createElement('div');
cssloadCheckNode.className = config.testDivClass;
document.getElementsByTagName("body")[0].appendChild(cssloadCheckNode);
if (cssloadCheckNode.offsetWidth != 100 && noMediaQuery == false) {
noMediaQuery = true;
}
cssloadCheckNode.parentNode.removeChild(cssloadCheckNode)
if (noMediaQuery == true) {
// Browser does not support Media Queries, so JavaScript will supply a fallback
var cssHref = "";
// Determines what CSS file to load
if (getWindowWidth() <= config.mobileMaxWidth) {
cssHref = config.cssHandheld;
newCssMediaType = "handheld";
} else {
cssHref = config.cssScreen;
newCssMediaType = "screen";
}
// Add CSS link to <head> of page
if (cssHref != "" && currentCssMediaType != newCssMediaType) {
var currentCssLinks = document.styleSheets
for (var i = 0; i < currentCssLinks.length; i++) {
for (var ii = 0; ii < currentCssLinks[i].media.length; ii++) {
if (typeof(currentCssLinks[i].media) == "object") {
if (currentCssLinks[i].media.item(ii) == "fallback") {
currentCssLinks[i].ownerNode.parentNode.removeChild(currentCssLinks[i].ownerNode)
i--
break;
}
} else {
if (currentCssLinks[i].media.indexOf("fallback") >= 0) {
currentCssLinks[i].owningElement.parentNode.removeChild(currentCssLinks[i].owningElement)
i--
break;
}
}
}
}
if (typeof(cssHref) == "object") {
for (var i = 0; i < cssHref.length; i++) {
addCssLink(cssHref[i])
}
} else {
addCssLink(cssHref)
}
currentCssMediaType = newCssMediaType;
}
// Check screen size again if user resizes window
addEvent(window, wbos.CssTools.MediaQueryFallBack.LoadCssDelayed, 'onresize')
}
},
/**
* Runs LoadCSS after a short delay
*
* @since 1.0 - 2010-08-21
* @version 1.0 - 2010-08-21
* @example
* wbos.CssTools.MediaQueryFallBack.LoadCssDelayed()
*/
LoadCssDelayed: function() {
clearTimeout(delay);
delay = setTimeout( "wbos.CssTools.MediaQueryFallBack.LoadCss()", config.resizeDelay)
}
}
/* End public */
})();
/**
* @namespace Adds a function to an event of a single element. Use this if
* you don't want to use jQuery
* @class
* @since 1.0 - 2010-02-23
* @version 1.0 - 2010-02-23
*/
wbos.Events = ( function() {
/* Start public */
return {
/**
* Adds a function to an event of a single element
*
* @since 1.0 - 2010-02-23
* @version 1.0 - 2010-02-23
* @param {Object} element The element on which the event is placed
* @param {Function} newFunction The function that has to be linked to the event
* @param {String} eventType Name of the event
* @example
* wbos.Events.AddEvent( document.getElementById('elementId'), functionName, "onclick" )
*/
AddEvent: function( element, newFunction, eventType ) {
var oldEvent = eval("element." + eventType);
var eventContentType = eval("typeof element." + eventType)
if ( eventContentType != 'function' ) {
eval("element." + eventType + " = newFunction")
} else {
eval("element." + eventType + " = function(e) { oldEvent(e); newFunction(e); }")
}
}
}
/* End public */
})();
if (typeof(codeview) == "undefined") {
/**
* @namespace Code written for the Codeview template
*/
codeview = {}
}
/**
* @namespace Enables filtering in class lists
* @class
* @since 1.0 - 2010-11-08
* @version 1.0 - 2010-11-08
*/
codeview.classFilter = ( function() {
function onkeyup_ClassFilter() {
var listItems
var search = document.getElementById('ClassFilter').value
search = search.toLowerCase()
if (document.getElementById('ClassList')) {
listItems = document.getElementById('ClassList').getElementsByTagName('li')
filterList(listItems, search)
}
if (document.getElementById('ClassList2')) {
listItems = document.getElementById('ClassList2').getElementsByTagName('li')
filterList(listItems, search)
}
if (document.getElementById('FileList')) {
listItems = document.getElementById('FileList').getElementsByTagName('li')
filterList(listItems, search)
}
if (document.getElementById('MethodsListInherited')) {
var links = document.getElementById('MethodsListInherited').getElementsByTagName('a')
var linksSelected = new Array()
for (var i=0; i < links.length; i++) {
if (links[i].parentNode.parentNode.tagName == "DD") {
linksSelected.push(links[i])
}
}
filterList(linksSelected, search)
}
if (document.getElementById('MethodsList')) {
listItems = document.getElementById('MethodsList').getElementsByTagName('tbody')[0].getElementsByTagName('tr')
filterList(listItems, search, document.getElementById('MethodDetail').getElementsByTagName('li'))
}
}
function filterList(listItems, search, relatedElements) {
var itemContent = ""
for (var i=0; i < listItems.length; i++) {
itemContent = listItems[i].textContent||listItems[i].innerText
if (itemContent != undefined) {
itemContent = itemContent.toLowerCase()
itemContent = itemContent.replace(/\s/g, "")
if (itemContent.indexOf(search) >= 0 || itemContent == "") {
listItems[i].style.display = ""
} else {
listItems[i].style.display = "none"
}
if (relatedElements != null) {
filterRelatedList(listItems[i], search, relatedElements)
}
}
}
}
function filterRelatedList(listItem, search, relatedElements) {
var itemIndex = parseInt(listItem.className.replace('item', ''))
if (itemIndex <= relatedElements.length) {
if (relatedElements[itemIndex].className == "item"+ itemIndex) {
relatedElements[itemIndex].style.display = listItem.style.display
}
}
}
/* Start public */
return {
Init: function() {
wbos.Events.AddEvent(
document.getElementById('ClassFilter'),
onkeyup_ClassFilter,
"onkeyup"
)
}
}
/* End public */
})();
| JavaScript |
/** Called automatically by JsDoc Toolkit. */
function publish(symbolSet) {
publish.conf = { // trailing slash expected for dirs
ext: ".html",
outDir: JSDOC.opt.d || SYS.pwd+"../out/jsdoc/",
templatesDir: JSDOC.opt.t || SYS.pwd+"../templates/jsdoc/",
symbolsDir: "symbols/",
srcDir: "symbols/src/"
};
// is source output is suppressed, just display the links to the source file
if (JSDOC.opt.s && defined(Link) && Link.prototype._makeSrcLink) {
Link.prototype._makeSrcLink = function(srcFilePath) {
return "<"+srcFilePath+">";
}
}
// create the folders and subfolders to hold the output
IO.mkPath((publish.conf.outDir+"symbols/src").split("/"));
// used to allow Link to check the details of things being linked to
Link.symbolSet = symbolSet;
// create the required templates
try {
var classTemplate = new JSDOC.JsPlate(publish.conf.templatesDir+"class.tmpl");
var classesTemplate = new JSDOC.JsPlate(publish.conf.templatesDir+"allclasses.tmpl");
}
catch(e) {
print("Couldn't create the required templates: "+e);
quit();
}
// some ustility filters
function hasNoParent($) {return ($.memberOf == "")}
function isaFile($) {return ($.is("FILE"))}
function isaClass($) {return ($.is("CONSTRUCTOR") || $.isNamespace)}
// get an array version of the symbolset, useful for filtering
var symbols = symbolSet.toArray();
// create the hilited source code files
var files = JSDOC.opt.srcFiles;
for (var i = 0, l = files.length; i < l; i++) {
var file = files[i];
var srcDir = publish.conf.outDir + "symbols/src/";
makeSrcFile(file, srcDir);
}
// get a list of all the classes in the symbolset
var classes = symbols.filter(isaClass).sort(makeSortby("alias"));
// create a filemap in which outfiles must be to be named uniquely, ignoring case
if (JSDOC.opt.u) {
var filemapCounts = {};
Link.filemap = {};
for (var i = 0, l = classes.length; i < l; i++) {
var lcAlias = classes[i].alias.toLowerCase();
if (!filemapCounts[lcAlias]) filemapCounts[lcAlias] = 1;
else filemapCounts[lcAlias]++;
Link.filemap[classes[i].alias] =
(filemapCounts[lcAlias] > 1)?
lcAlias+"_"+filemapCounts[lcAlias] : lcAlias;
}
}
// create a class index, displayed in the left-hand column of every class page
Link.base = "../";
publish.classesIndex = classesTemplate.process(classes); // kept in memory
// create each of the class pages
for (var i = 0, l = classes.length; i < l; i++) {
var symbol = classes[i];
symbol.events = symbol.getEvents(); // 1 order matters
symbol.methods = symbol.getMethods(); // 2
Link.currentSymbol= symbol;
var output = "";
output = classTemplate.process(symbol);
IO.saveFile(publish.conf.outDir+"symbols/", ((JSDOC.opt.u)? Link.filemap[symbol.alias] : symbol.alias) + publish.conf.ext, output);
}
// regenerate the index with different relative links, used in the index pages
Link.base = "";
publish.classesIndex = classesTemplate.process(classes);
// create the class index page
try {
var classesindexTemplate = new JSDOC.JsPlate(publish.conf.templatesDir+"index.tmpl");
}
catch(e) { print(e.message); quit(); }
var classesIndex = classesindexTemplate.process(classes);
IO.saveFile(publish.conf.outDir, "index"+publish.conf.ext, classesIndex);
classesindexTemplate = classesIndex = classes = null;
// create the file index page
try {
var fileindexTemplate = new JSDOC.JsPlate(publish.conf.templatesDir+"allfiles.tmpl");
}
catch(e) { print(e.message); quit(); }
var documentedFiles = symbols.filter(isaFile); // files that have file-level docs
var allFiles = []; // not all files have file-level docs, but we need to list every one
for (var i = 0; i < files.length; i++) {
allFiles.push(new JSDOC.Symbol(files[i], [], "FILE", new JSDOC.DocComment("/** */")));
}
for (var i = 0; i < documentedFiles.length; i++) {
var offset = files.indexOf(documentedFiles[i].alias);
allFiles[offset] = documentedFiles[i];
}
allFiles = allFiles.sort(makeSortby("name"));
// output the file index page
var filesIndex = fileindexTemplate.process(allFiles);
IO.saveFile(publish.conf.outDir, "files"+publish.conf.ext, filesIndex);
fileindexTemplate = filesIndex = files = null;
}
/** Just the first sentence (up to a full stop). Should not break on dotted variable names. */
function summarize(desc) {
if (typeof desc != "undefined")
return desc.match(/([\w\W]+?\.)[^a-z0-9_$]/i)? RegExp.$1 : desc;
}
/** Make a symbol sorter by some attribute. */
function makeSortby(attribute) {
return function(a, b) {
if (a[attribute] != undefined && b[attribute] != undefined) {
a = a[attribute].toLowerCase();
b = b[attribute].toLowerCase();
if (a < b) return -1;
if (a > b) return 1;
return 0;
}
}
}
/** Pull in the contents of an external file at the given path. */
function include(path) {
var path = publish.conf.templatesDir+path;
return IO.readFile(path);
}
/** Turn a raw source file into a code-hilited page in the docs. */
function makeSrcFile(path, srcDir, name) {
if (JSDOC.opt.s) return;
if (!name) {
name = path.replace(/\.\.?[\\\/]/g, "").replace(/[\\\/]/g, "_");
name = name.replace(/\:/g, "_");
}
var src = {path: path, name:name, charset: IO.encoding, hilited: ""};
if (defined(JSDOC.PluginManager)) {
JSDOC.PluginManager.run("onPublishSrc", src);
}
if (src.hilited) {
IO.saveFile(srcDir, name+publish.conf.ext, src.hilited);
}
}
/** Build output for displaying function parameters. */
function makeSignature(params) {
if (!params) return "()";
var signature = "("
+
params.filter(
function($) {
return $.name.indexOf(".") == -1; // don't show config params in signature
}
).map(
function($) {
return $.name;
}
).join(", ")
+
")";
return signature;
}
/** Find symbol {@link ...} strings in text and turn into html links */
function resolveLinks(str, from) {
str = str.replace(/\{@link ([^} ]+) ?\}/gi,
function(match, symbolName) {
return new Link().toSymbol(symbolName);
}
);
return str;
}
| JavaScript |
/**
* @fileOverview Contains standard code in the namespace 'wbos' and code specifically written for Codeview in the namespace 'codeview'
* @author Wouter Bos (www.thebrightlines.com)
* @since 1.0 - 2010-09-10
* @version 1.0 - 2010-09-10
*/
if (typeof(wbos) == "undefined") {
/**
* @namespace Standard code of Wouter Bos (wbos)
*/
wbos = {}
}
if (typeof(wbos.CssTools) == "undefined") {
/**
* @namespace Namespace for CSS-related functionality
*/
wbos.CssTools = {}
}
/**
* @namespace Fallback for CSS advanced media query
* @class
* @since 1.0 - 2010-09-10
* @version 1.0 - 2010-09-10
*/
wbos.CssTools.MediaQueryFallBack = ( function() {
var config = {
cssScreen: "/css/screen.css",
cssHandheld: "/css/handheld.css",
mobileMaxWidth: 660,
testDivClass: "cssLoadCheck",
dynamicCssLinkId: "DynCssLink",
resizeDelay: 30
}
var noMediaQuery = false;
var delay;
var currentCssMediaType;
// Adding events to elements in the DOM without overwriting it
function addEvent(element, newFunction, eventType) {
var oldEvent = eval("element." + eventType);
var eventContentType = eval("typeof element." + eventType)
if ( eventContentType != 'function' ) {
eval("element." + eventType + " = newFunction")
} else {
eval("element." + eventType + " = function(e) { oldEvent(e); newFunction(e); }")
}
}
// Get the the inner width of the browser window
function getWindowWidth() {
if (window.innerWidth) {
return window.innerWidth;
} else if (document.documentElement.clientWidth) {
return document.documentElement.clientWidth;
} else if (document.body.clientWidth) {
return document.body.clientWidth;
} else{
return 0;
}
}
function addCssLink(cssHref) {
var cssNode = document.createElement('link');
var windowWidth;
cssNode.type = 'text/css';
cssNode.rel = 'stylesheet';
cssNode.media = 'screen, handheld, fallback';
cssNode.href = cssHref;
document.getElementsByTagName("head")[0].appendChild(cssNode);
}
/* Start public */
return {
/**
* Adds link to CSS in the head if no CSS is loaded
*
* @since 1.0 - 2010-08-21
* @version 1.0 - 2010-08-21
* @param {String|Object} cssScreen URL to CSS file for larger screens
* @param {String|Object} cssHandheld URL to CSS file for smaller screens
* @param {Number} mobileMaxWidth Maximum width for handheld devices
* @example
* wbos.CssTools.MediaQueryFallBack.LoadCss(['screen.css', 'screen2.css'], 'mobile.css', 480)
*/
LoadCss: function(cssScreen, cssHandheld, mobileMaxWidth) {
// Set config values
if (typeof(cssScreen) != "undefined") {
config.cssScreen = cssScreen;
}
if (typeof(cssHandheld) != "undefined") {
config.cssHandheld = cssHandheld;
}
if (typeof(mobileMaxWidth) != "undefined") {
config.mobileMaxWidth = mobileMaxWidth;
}
// Check if CSS is loaded
var cssloadCheckNode = document.createElement('div');
cssloadCheckNode.className = config.testDivClass;
document.getElementsByTagName("body")[0].appendChild(cssloadCheckNode);
if (cssloadCheckNode.offsetWidth != 100 && noMediaQuery == false) {
noMediaQuery = true;
}
cssloadCheckNode.parentNode.removeChild(cssloadCheckNode)
if (noMediaQuery == true) {
// Browser does not support Media Queries, so JavaScript will supply a fallback
var cssHref = "";
// Determines what CSS file to load
if (getWindowWidth() <= config.mobileMaxWidth) {
cssHref = config.cssHandheld;
newCssMediaType = "handheld";
} else {
cssHref = config.cssScreen;
newCssMediaType = "screen";
}
// Add CSS link to <head> of page
if (cssHref != "" && currentCssMediaType != newCssMediaType) {
var currentCssLinks = document.styleSheets
for (var i = 0; i < currentCssLinks.length; i++) {
for (var ii = 0; ii < currentCssLinks[i].media.length; ii++) {
if (typeof(currentCssLinks[i].media) == "object") {
if (currentCssLinks[i].media.item(ii) == "fallback") {
currentCssLinks[i].ownerNode.parentNode.removeChild(currentCssLinks[i].ownerNode)
i--
break;
}
} else {
if (currentCssLinks[i].media.indexOf("fallback") >= 0) {
currentCssLinks[i].owningElement.parentNode.removeChild(currentCssLinks[i].owningElement)
i--
break;
}
}
}
}
if (typeof(cssHref) == "object") {
for (var i = 0; i < cssHref.length; i++) {
addCssLink(cssHref[i])
}
} else {
addCssLink(cssHref)
}
currentCssMediaType = newCssMediaType;
}
// Check screen size again if user resizes window
addEvent(window, wbos.CssTools.MediaQueryFallBack.LoadCssDelayed, 'onresize')
}
},
/**
* Runs LoadCSS after a short delay
*
* @since 1.0 - 2010-08-21
* @version 1.0 - 2010-08-21
* @example
* wbos.CssTools.MediaQueryFallBack.LoadCssDelayed()
*/
LoadCssDelayed: function() {
clearTimeout(delay);
delay = setTimeout( "wbos.CssTools.MediaQueryFallBack.LoadCss()", config.resizeDelay)
}
}
/* End public */
})();
/**
* @namespace Adds a function to an event of a single element. Use this if
* you don't want to use jQuery
* @class
* @since 1.0 - 2010-02-23
* @version 1.0 - 2010-02-23
*/
wbos.Events = ( function() {
/* Start public */
return {
/**
* Adds a function to an event of a single element
*
* @since 1.0 - 2010-02-23
* @version 1.0 - 2010-02-23
* @param {Object} element The element on which the event is placed
* @param {Function} newFunction The function that has to be linked to the event
* @param {String} eventType Name of the event
* @example
* wbos.Events.AddEvent( document.getElementById('elementId'), functionName, "onclick" )
*/
AddEvent: function( element, newFunction, eventType ) {
var oldEvent = eval("element." + eventType);
var eventContentType = eval("typeof element." + eventType)
if ( eventContentType != 'function' ) {
eval("element." + eventType + " = newFunction")
} else {
eval("element." + eventType + " = function(e) { oldEvent(e); newFunction(e); }")
}
}
}
/* End public */
})();
if (typeof(codeview) == "undefined") {
/**
* @namespace Code written for the Codeview template
*/
codeview = {}
}
/**
* @namespace Enables filtering in class lists
* @class
* @since 1.0 - 2010-11-08
* @version 1.0 - 2010-11-08
*/
codeview.classFilter = ( function() {
function onkeyup_ClassFilter() {
var listItems
var search = document.getElementById('ClassFilter').value
search = search.toLowerCase()
if (document.getElementById('ClassList')) {
listItems = document.getElementById('ClassList').getElementsByTagName('li')
filterList(listItems, search)
}
if (document.getElementById('ClassList2')) {
listItems = document.getElementById('ClassList2').getElementsByTagName('li')
filterList(listItems, search)
}
if (document.getElementById('FileList')) {
listItems = document.getElementById('FileList').getElementsByTagName('li')
filterList(listItems, search)
}
if (document.getElementById('MethodsListInherited')) {
var links = document.getElementById('MethodsListInherited').getElementsByTagName('a')
var linksSelected = new Array()
for (var i=0; i < links.length; i++) {
if (links[i].parentNode.parentNode.tagName == "DD") {
linksSelected.push(links[i])
}
}
filterList(linksSelected, search)
}
if (document.getElementById('MethodsList')) {
listItems = document.getElementById('MethodsList').getElementsByTagName('tbody')[0].getElementsByTagName('tr')
filterList(listItems, search, document.getElementById('MethodDetail').getElementsByTagName('li'))
}
}
function filterList(listItems, search, relatedElements) {
var itemContent = ""
for (var i=0; i < listItems.length; i++) {
itemContent = listItems[i].textContent||listItems[i].innerText
if (itemContent != undefined) {
itemContent = itemContent.toLowerCase()
itemContent = itemContent.replace(/\s/g, "")
if (itemContent.indexOf(search) >= 0 || itemContent == "") {
listItems[i].style.display = ""
} else {
listItems[i].style.display = "none"
}
if (relatedElements != null) {
filterRelatedList(listItems[i], search, relatedElements)
}
}
}
}
function filterRelatedList(listItem, search, relatedElements) {
var itemIndex = parseInt(listItem.className.replace('item', ''))
if (itemIndex <= relatedElements.length) {
if (relatedElements[itemIndex].className == "item"+ itemIndex) {
relatedElements[itemIndex].style.display = listItem.style.display
}
}
}
/* Start public */
return {
Init: function() {
wbos.Events.AddEvent(
document.getElementById('ClassFilter'),
onkeyup_ClassFilter,
"onkeyup"
)
}
}
/* End public */
})();
| JavaScript |
/** Called automatically by JsDoc Toolkit. */
function publish(symbolSet) {
publish.conf = { // trailing slash expected for dirs
ext: ".html",
outDir: JSDOC.opt.d || SYS.pwd+"../out/jsdoc/",
templatesDir: JSDOC.opt.t || SYS.pwd+"../templates/jsdoc/",
staticDir: "static/",
symbolsDir: "symbols/",
srcDir: "symbols/src/",
cssDir: "css/",
fontsDir: "css/fonts/",
jsDir: "javascript/",
templateName: "Codeview",
templateVersion: "1.2",
templateLink: "http://www.thebrightlines.com/2010/05/06/new-template-for-jsdoctoolkit-codeview/"
};
// is source output is suppressed, just display the links to the source file
if (JSDOC.opt.s && defined(Link) && Link.prototype._makeSrcLink) {
Link.prototype._makeSrcLink = function(srcFilePath) {
return "<"+srcFilePath+">";
}
}
// create the folders and subfolders to hold the output
IO.mkPath((publish.conf.outDir+publish.conf.cssDir));
IO.mkPath((publish.conf.outDir+publish.conf.fontsDir));
IO.mkPath((publish.conf.outDir+publish.conf.jsDir));
IO.mkPath((publish.conf.outDir+"symbols/src").split("/"));
// used to allow Link to check the details of things being linked to
Link.symbolSet = symbolSet;
// create the required templates
try {
var classTemplate = new JSDOC.JsPlate(publish.conf.templatesDir+"class.tmpl");
}
catch(e) {
print("Couldn't create the required templates: "+e);
quit();
}
// some utility filters
function hasNoParent($) {return ($.memberOf == "")}
function isaFile($) {return ($.is("FILE"))}
function isaClass($) {return (($.is("CONSTRUCTOR") || $.isNamespace) && ($.alias != "_global_" || !JSDOC.opt.D.noGlobal))}
// get an array version of the symbolset, useful for filtering
var symbols = symbolSet.toArray();
// create the hilited source code files
var files = JSDOC.opt.srcFiles;
for (var i = 0, l = files.length; i < l; i++) {
var file = files[i];
var srcDir = publish.conf.outDir + publish.conf.srcDir;
makeSrcFile(file, srcDir);
}
// get a list of all the classes in the symbolset
publish.classes = symbols.filter(isaClass).sort(makeSortby("alias"));
// create a filemap in which outfiles must be to be named uniquely, ignoring case
if (JSDOC.opt.u) {
var filemapCounts = {};
Link.filemap = {};
for (var i = 0, l = publish.classes.length; i < l; i++) {
var lcAlias = publish.classes[i].alias.toLowerCase();
if (!filemapCounts[lcAlias]) filemapCounts[lcAlias] = 1;
else filemapCounts[lcAlias]++;
Link.filemap[publish.classes[i].alias] =
(filemapCounts[lcAlias] > 1)?
lcAlias+"_"+filemapCounts[lcAlias] : lcAlias;
}
}
// create each of the class pages
for (var i = 0, l = publish.classes.length; i < l; i++) {
var symbol = publish.classes[i];
symbol.events = symbol.getEvents(); // 1 order matters
symbol.methods = symbol.getMethods(); // 2
var output = "";
output = classTemplate.process(symbol);
IO.saveFile(publish.conf.outDir+publish.conf.symbolsDir, ((JSDOC.opt.u)? Link.filemap[symbol.alias] : symbol.alias) + publish.conf.ext, output);
}
// create the class index page
try {
var classesindexTemplate = new JSDOC.JsPlate(publish.conf.templatesDir+"allclasses.tmpl");
}
catch(e) { print(e.message); quit(); }
var classesIndex = classesindexTemplate.process(publish.classes);
IO.saveFile(publish.conf.outDir, (JSDOC.opt.D.index=="files"?"allclasses":"index")+publish.conf.ext, classesIndex);
classesindexTemplate = classesIndex = classes = null;
// create the file index page
try {
var fileindexTemplate = new JSDOC.JsPlate(publish.conf.templatesDir+"allfiles.tmpl");
}
catch(e) { print(e.message); quit(); }
var documentedFiles = symbols.filter(isaFile); // files that have file-level docs
var allFiles = []; // not all files have file-level docs, but we need to list every one
for (var i = 0; i < files.length; i++) {
allFiles.push(new JSDOC.Symbol(files[i], [], "FILE", new JSDOC.DocComment("/** */")));
}
for (var i = 0; i < documentedFiles.length; i++) {
var offset = files.indexOf(documentedFiles[i].alias);
allFiles[offset] = documentedFiles[i];
}
allFiles = allFiles.sort(makeSortby("name"));
// output the file index page
var filesIndex = fileindexTemplate.process(allFiles);
IO.saveFile(publish.conf.outDir, (JSDOC.opt.D.index=="files"?"index":"files")+publish.conf.ext, filesIndex);
fileindexTemplate = filesIndex = files = null;
// copy static files
IO.copyFile(publish.conf.templatesDir+"/"+publish.conf.cssDir+"all.css", publish.conf.outDir+"/"+publish.conf.cssDir);
IO.copyFile(publish.conf.templatesDir+"/"+publish.conf.cssDir+"screen.css", publish.conf.outDir+"/"+publish.conf.cssDir);
IO.copyFile(publish.conf.templatesDir+"/"+publish.conf.cssDir+"handheld.css", publish.conf.outDir+"/"+publish.conf.cssDir);
IO.copyFile(publish.conf.templatesDir+"/"+publish.conf.jsDir+"all.js", publish.conf.outDir+"/"+publish.conf.jsDir);
IO.copyFile(publish.conf.templatesDir+"/"+publish.conf.jsDir+"html5.js", publish.conf.outDir+"/"+publish.conf.jsDir);
IO.copyFile(publish.conf.templatesDir+"/"+publish.conf.fontsDir+"mplus-1m-regular-webfont.eot", publish.conf.outDir+"/"+publish.conf.fontsDir);
IO.copyFile(publish.conf.templatesDir+"/"+publish.conf.fontsDir+"mplus-1m-regular-webfont.svg", publish.conf.outDir+"/"+publish.conf.fontsDir);
IO.copyFile(publish.conf.templatesDir+"/"+publish.conf.fontsDir+"mplus-1m-regular-webfont.ttf", publish.conf.outDir+"/"+publish.conf.fontsDir);
IO.copyFile(publish.conf.templatesDir+"/"+publish.conf.fontsDir+"mplus-1m-regular-webfont.woff", publish.conf.outDir+"/"+publish.conf.fontsDir);
IO.copyFile(publish.conf.templatesDir+"/"+publish.conf.fontsDir+"mplus-1m-bold-webfont.eot", publish.conf.outDir+"/"+publish.conf.fontsDir);
IO.copyFile(publish.conf.templatesDir+"/"+publish.conf.fontsDir+"mplus-1m-bold-webfont.svg", publish.conf.outDir+"/"+publish.conf.fontsDir);
IO.copyFile(publish.conf.templatesDir+"/"+publish.conf.fontsDir+"mplus-1m-bold-webfont.ttf", publish.conf.outDir+"/"+publish.conf.fontsDir);
IO.copyFile(publish.conf.templatesDir+"/"+publish.conf.fontsDir+"mplus-1m-bold-webfont.woff", publish.conf.outDir+"/"+publish.conf.fontsDir); }
/** Include a sub-template in the current template, specifying a data object */
function subtemplate(template, data) {
try {
return new JSDOC.JsPlate(publish.conf.templatesDir+template).process(data);
}
catch(e) { print(e.message); quit(); }
}
/** Just the first sentence (up to a full stop). Should not break on dotted variable names. */
function summarize(desc) {
if (typeof desc != "undefined")
return desc.match(/([\w\W]+?\.)[^a-z0-9_$]/i)? RegExp.$1 : desc;
}
/** Make a symbol sorter by some attribute. */
function makeSortby(attribute) {
return function(a, b) {
if (a[attribute] != undefined && b[attribute] != undefined) {
a = a[attribute].toLowerCase();
b = b[attribute].toLowerCase();
if (a < b) return -1;
if (a > b) return 1;
return 0;
}
}
}
function wordwrapNamespace(classLink) {
var classText = classLink.match(/[^<>]+(?=[<])/) + "";
var classTextNew = classText.replace(/\./g, "<span class='break'> </span>.<span class='break'> </span>") + "";
classLink = classLink.replace(/[^<>]+(?=[<])/, classTextNew);
return classLink;
}
/** Pull in the contents of an external file at the given path. */
function include(path) {
var path = publish.conf.templatesDir+path;
return IO.readFile(path);
}
/** Turn a raw source file into a code-hilited page in the docs. */
function makeSrcFile(path, srcDir, name) {
if (JSDOC.opt.s) return;
if (!name) {
name = path.replace(/\.\.?[\\\/]/g, "").replace(/[\\\/]/g, "_");
name = name.replace(/\:/g, "_");
}
var src = {path: path, name:name, charset: IO.encoding, hilited: ""};
if (defined(JSDOC.PluginManager)) {
JSDOC.PluginManager.run("onPublishSrc", src);
}
if (src.hilited) {
IO.saveFile(srcDir, name+publish.conf.ext, src.hilited);
}
}
/** Build output for displaying function parameters. */
function makeSignature(params) {
if (!params) return "()";
var signature = "("
+
params.filter(
function($) {
return $.name.indexOf(".") == -1; // don't show config params in signature
}
).map(
function($) {
return $.name;
}
).join(", ")
+
")";
return signature;
}
/** Find symbol {@link ...} strings in text and turn into html links */
function resolveLinks(str, from) {
str = str.replace(/\{@link ([^}]+)\}/gi,
function(match, symbolName) {
symbolName = symbolName.trim();
var index = symbolName.indexOf(' ');
if (index > 0) {
var label = symbolName.substring(index + 1);
symbolName = symbolName.substring(0, index);
return new Link().toSymbol(symbolName).withText(label);
} else {
return new Link().toSymbol(symbolName);
}
}
);
return str;
} | JavaScript |
/**
This is the main container for the FOODOC handler.
@namespace
*/
FOODOC = {
};
/** The current version string of this application. */
FOODOC.VERSION = "1.0";
FOODOC.handle = function(srcFile, src) {
LOG.inform("Handling file '" + srcFile + "'");
return [
new JSDOC.Symbol(
"foo",
[],
"VIRTUAL",
new JSDOC.DocComment("/** This is a foo. */")
)
];
};
FOODOC.publish = function(symbolgroup) {
LOG.inform("Publishing symbolgroup.");
};
| JavaScript |
/**
* This is the main container for the XMLDOC handler.
* @namespace
* @author Brett Fattori (bfattori@fry.com)
* @version $Revision: 498 $
*/
XMLDOC = {
};
/** The current version string of this application. */
XMLDOC.VERSION = "1.0";
/** Include the library necessary to handle XML files */
IO.includeDir("handlers/XMLDOC/");
/**
* @type Symbol[]
*/
XMLDOC.handle = function(srcFile, src) {
};
XMLDOC.publish = function(symbolgroup) {
} | JavaScript |
LOG.inform("XMLDOC.DomReader loaded");
XMLDOC.DomReader = function(root) {
this.dom = root;
/**
* The current node the reader is on
*/
this.node = root;
/**
* Get the current node the reader is on
* @type XMLDOC.Parser.node
*/
XMLDOC.DomReader.prototype.getNode = function() {
return this.node;
};
/**
* Set the node the reader should be positioned on.
* @param node {XMLDOC.Parser.node}
*/
XMLDOC.DomReader.prototype.setNode = function(node) {
this.node = node;
};
/**
* A helper method to make sure the current node will
* never return null, unless null is passed as the root.
* @param step {String} An expression to evaluate - should return a node or null
*/
XMLDOC.DomReader.prototype.navigate = function(step) {
var n;
if ((n = step) != null)
{
this.node = n;
return this.node;
}
return null;
};
/**
* Get the root node of the current node's document.
*/
XMLDOC.DomReader.prototype.root = function() {
this.navigate(this.dom);
};
/**
* Get the parent of the current node.
*/
XMLDOC.DomReader.prototype.parent = function() {
return this.navigate(this.node.parentNode());
};
/**
* Get the first child of the current node.
*/
XMLDOC.DomReader.prototype.firstChild = function() {
return this.navigate(this.node.firstChild());
};
/**
* Get the last child of the current node.
*/
XMLDOC.DomReader.prototype.lastChild = function() {
return this.navigate(this.node.lastChild());
};
/**
* Get the next sibling of the current node.
*/
XMLDOC.DomReader.prototype.nextSibling = function() {
return this.navigate(this.node.nextSibling());
};
/**
* Get the previous sibling of the current node.
*/
XMLDOC.DomReader.prototype.prevSibling = function() {
return this.navigate(this.node.prevSibling());
};
//===============================================================================================
// Support methods
/**
* Walk the tree starting with the current node, calling the plug-in for
* each node visited. Each time the plug-in is called, the DomReader
* is passed as the only parameter. Use the {@link XMLDOC.DomReader#getNode} method
* to access the current node. <i>This method uses a depth first traversal pattern.</i>
*
* @param srcFile {String} The source file being evaluated
*/
XMLDOC.DomReader.prototype.getSymbols = function(srcFile)
{
XMLDOC.DomReader.symbols = [];
XMLDOC.DomReader.currentFile = srcFile;
JSDOC.Symbol.srcFile = (srcFile || "");
if (defined(JSDOC.PluginManager)) {
JSDOC.PluginManager.run("onDomGetSymbols", this);
}
return XMLDOC.DomReader.symbols;
};
/**
* Find the node with the given name using a depth first traversal.
* Does not modify the DomReader's current node.
*
* @param name {String} The name of the node to find
* @return the node that was found, or null if not found
*/
XMLDOC.DomReader.prototype.findNode = function(name)
{
var findNode = null;
// Start at the current node and move into the subtree,
// looking for the node with the given name
function deeper(node, find)
{
var look = null;
if (node) {
if (node.name == find)
{
return node;
}
if (node.firstChild())
{
look = deeper(node.firstChild(), find);
}
if (!look && node.nextSibling())
{
look = deeper(node.nextSibling(), find);
}
}
return look;
}
return deeper(this.getNode().firstChild(), name);
};
/**
* Find the next node with the given name using a depth first traversal.
*
* @param name {String} The name of the node to find
*/
XMLDOC.DomReader.prototype.findPreviousNode = function(name)
{
};
};
| JavaScript |
LOG.inform("XMLDOC.Parser loaded");
/**
* XML Parser object. Returns an {@link #XMLDOC.Parser.node} which is
* the root element of the parsed document.
* <p/>
* By default, this parser will only handle well formed XML. To
* allow the parser to handle HTML, set the <tt>XMLDOC.Parser.strictMode</tt>
* variable to <tt>false</tt> before calling <tt>XMLDOC.Parser.parse()</tt>.
* <p/>
* <i>Note: If you pass poorly formed XML, it will cause the parser to throw
* an exception.</i>
*
* @author Brett Fattori (bfattori@fry.com)
* @author $Author: micmath $
* @version $Revision: 497 $
*/
XMLDOC.Parser = {};
/**
* Strict mode setting. Setting this to false allows HTML-style source to
* be parsed. Normally, well formed XML has defined end tags, or empty tags
* are properly formed. Default: <tt>true</tt>
* @type Boolean
*/
XMLDOC.Parser.strictMode = true;
/**
* A node in an XML Document. Node types are ROOT, ELEMENT, COMMENT, PI, and TEXT.
* @param parent {XMLDOC.Parser.node} The parent node
* @param name {String} The node name
* @param type {String} One of the types
*/
XMLDOC.Parser.node = function(parent, name, type)
{
this.name = name;
this.type = type || "ELEMENT";
this.parent = parent;
this.charData = "";
this.attrs = {};
this.nodes = [];
this.cPtr = 0;
XMLDOC.Parser.node.prototype.getAttributeNames = function() {
var a = [];
for (var o in this.attrs)
{
a.push(o);
}
return a;
};
XMLDOC.Parser.node.prototype.getAttribute = function(attr) {
return this.attrs[attr];
};
XMLDOC.Parser.node.prototype.setAttribute = function(attr, val) {
this.attrs[attr] = val;
};
XMLDOC.Parser.node.prototype.getChild = function(idx) {
return this.nodes[idx];
};
XMLDOC.Parser.node.prototype.parentNode = function() {
return this.parent;
};
XMLDOC.Parser.node.prototype.firstChild = function() {
return this.nodes[0];
};
XMLDOC.Parser.node.prototype.lastChild = function() {
return this.nodes[this.nodes.length - 1];
};
XMLDOC.Parser.node.prototype.nextSibling = function() {
var p = this.parent;
if (p && (p.nodes.indexOf(this) + 1 != p.nodes.length))
{
return p.getChild(p.nodes.indexOf(this) + 1);
}
return null;
};
XMLDOC.Parser.node.prototype.prevSibling = function() {
var p = this.parent;
if (p && (p.nodes.indexOf(this) - 1 >= 0))
{
return p.getChild(p.nodes.indexOf(this) - 1);
}
return null;
};
};
/**
* Parse an XML Document from the specified source. The XML should be
* well formed, unless strict mode is disabled, then the parser will
* handle HTML-style XML documents.
* @param src {String} The source to parse
*/
XMLDOC.Parser.parse = function(src)
{
var A = [];
// Normailize whitespace
A = src.split("\r\n");
src = A.join("\n");
A = src.split("\r");
src = A.join("\n");
// Remove XML and DOCTYPE specifier
src.replace(/<\?XML .*\?>/i, "");
src.replace(/<!DOCTYPE .*\>/i, "");
// The document is the root node and cannot be modified or removed
var doc = new XMLDOC.Parser.node(null, "ROOT", "DOCUMENT");
// Let's break it down
XMLDOC.Parser.eat(doc, src);
return doc;
};
/**
* The XML fragment processing routine. This method is private and should not be called
* directly.
* @param parentNode {XMLDOC.Parser.node} The node which is the parent of this fragment
* @param src {String} The source within the fragment to process
* @private
*/
XMLDOC.Parser.eat = function(parentNode, src)
{
// A simple tag def
var reTag = new RegExp("<(!|)(\\?|--|)((.|\\s)*?)\\2>","g");
// Special tag types
var reCommentTag = /<!--((.|\s)*?)-->/;
var rePITag = /<\?((.|\s)*?)\?>/;
// A start tag (with potential empty marker)
var reStartTag = /<(.*?)( +([\w_\-]*)=(\"|')(.*)\4)*(\/)?>/;
// An empty HTML style tag (not proper XML, but we'll accept it so we can process HTML)
var reHTMLEmptyTag = /<(.*?)( +([\w_\-]*)=(\"|')(.*)\4)*>/;
// Fully enclosing tag with nested tags
var reEnclosingTag = /<(.*?)( +([\w_\-]*)=(\"|')(.*?)\4)*>((.|\s)*?)<\/\1>/;
// Breaks down attributes
var reAttributes = new RegExp(" +([\\w_\\-]*)=(\"|')(.*?)\\2","g");
// Find us a tag
var tag;
while ((tag = reTag.exec(src)) != null)
{
if (tag.index > 0)
{
// The next tag has some text before it
var text = src.substring(0, tag.index).replace(/^[ \t\n]+((.|\n)*?)[ \t\n]+$/, "$1");
if (text.length > 0 && (text != "\n"))
{
var txtnode = new XMLDOC.Parser.node(parentNode, "", "TEXT");
txtnode.charData = text;
// Append the new text node
parentNode.nodes.push(txtnode);
}
// Reset the lastIndex of reTag
reTag.lastIndex -= src.substring(0, tag.index).length;
// Eat the text
src = src.substring(tag.index);
}
if (reCommentTag.test(tag[0]))
{
// Is this a comment?
var comment = new XMLDOC.Parser.node(parentNode, "", "COMMENT");
comment.charData = reCommentTag.exec(tag[0])[1];
// Append the comment
parentNode.nodes.push(comment);
// Move the lastIndex of reTag
reTag.lastIndex -= tag[0].length;
// Eat the tag
src = src.replace(reCommentTag, "");
}
else if (rePITag.test(tag[0]))
{
// Is this a processing instruction?
var pi = new XMLDOC.Parser.node(parentNode, "", "PI");
pi.charData = rePITag.exec(tag[0])[1];
// Append the processing instruction
parentNode.nodes.push(pi);
// Move the lastIndex of reTag
reTag.lastIndex -= tag[0].length;
// Eat the tag
src = src.replace(rePITag, "");
}
else if (reStartTag.test(tag[0]))
{
// Break it down
var e = reStartTag.exec(tag[0]);
var elem = new XMLDOC.Parser.node(parentNode, e[1], "ELEMENT");
// Get attributes from the tag
var a;
while ((a = reAttributes.exec(e[2])) != null )
{
elem.attrs[a[1]] = a[3];
}
// Is this an empty XML-style tag?
if (e[6] == "/")
{
// Append the empty element
parentNode.nodes.push(elem);
// Move the lastIndex of reTag (include the start tag length)
reTag.lastIndex -= e[0].length;
// Eat the tag
src = src.replace(reStartTag, "");
}
else
{
// Check for malformed XML tags
var htmlParsed = false;
var htmlStartTag = reHTMLEmptyTag.exec(src);
// See if there isn't an end tag within this block
var reHTMLEndTag = new RegExp("</" + htmlStartTag[1] + ">");
var htmlEndTag = reHTMLEndTag.exec(src);
if (XMLDOC.Parser.strictMode && htmlEndTag == null)
{
// Poorly formed XML fails in strict mode
var err = new Error("Malformed XML passed to XMLDOC.Parser... Error contains malformed 'src'");
err.src = src;
throw err;
}
else if (htmlEndTag == null)
{
// This is an HTML-style empty tag, store the element for it in non-strict mode
parentNode.nodes.push(elem);
// Eat the tag
src = src.replace(reHTMLEmptyTag, "");
htmlParsed = true;
}
// If we didn't parse HTML-style, it must be an enclosing tag
if (!htmlParsed)
{
var enc = reEnclosingTag.exec(src);
// Go deeper into the document
XMLDOC.Parser.eat(elem, enc[6]);
// Append the new element node
parentNode.nodes.push(elem);
// Eat the tag
src = src.replace(reEnclosingTag, "");
}
}
// Reset the lastIndex of reTag
reTag.lastIndex = 0;
}
}
// No tag was found... append the text if there is any
src = src.replace(/^[ \t\n]+((.|\n)*?)[ \t\n]+$/, "$1");
if (src.length > 0 && (src != "\n"))
{
var txtNode = new XMLDOC.Parser.node(parentNode, "", "TEXT");
txtNode.charData = src;
// Append the new text node
parentNode.nodes.push(txtNode);
}
};
| JavaScript |
LOG.inform("XMLDOC.symbolize loaded");
/**
* Convert the source file to a set of symbols
*/
XMLDOC.symbolize = function(srcFile, src) {
LOG.inform("Symbolizing file '" + srcFile + "'");
// XML files already have a defined structure, so we don't need to
// do anything but parse them. The DOM reader can create a symbol
// table from the parsed XML.
var dr = new XMLDOC.DomReader(XMLDOC.Parser.parse(src));
return dr.getSymbols(srcFile);
};
| JavaScript |
var TestDoc = {
fails: 0,
plans: 0,
passes: 0,
results: []
};
TestDoc.record = function(result) {
TestDoc.results.push(result);
if (typeof result.verdict == "boolean") {
if (result.verdict === false) TestDoc.fails++;
if (result.verdict === true) TestDoc.passes++;
}
}
TestDoc.prove = function(filePath) {
if (typeof document != "undefined" && typeof document.write != "undefined") {
if (TestDoc.console) print = function(s) { TestDoc.console.appendChild(document.createTextNode(s+"\n")); }
else print = function(s) { document.write(s+"<br />"); }
}
TestDoc.run(TestDoc.readFile(filePath));
}
TestDoc.run = function(src) {
try { eval(src); } catch(e) { print("# ERROR! "+e); }
var chunks = src.split(/\/\*t:/);
var run = function(chunk) {
// local shortcuts
var is = TestDoc.assertEquals;
var isnt = TestDoc.assertNotEquals;
var plan = TestDoc.plan;
var requires = TestDoc.requires;
try { eval(chunk); } catch(e) { print("# ERROR! "+e); }
}
for (var start = -1, end = 0; (start = src.indexOf("/*t:", end)) > end; start = end) {
run(
src.substring(
start+4,
(end = src.indexOf("*/", start))
)
);
}
}
TestDoc.Result = function(verdict, message) {
this.verdict = verdict;
this.message = message;
}
TestDoc.Result.prototype.toString = function() {
if (typeof this.verdict == "boolean") {
return (this.verdict? "ok" : "not ok") + " " + (++TestDoc.report.counter) + " - " + this.message;
}
return "# " + this.message;
}
TestDoc.requires = function(file) {
if (!TestDoc.requires.loaded[file]) {
load(file);
TestDoc.requires.loaded[file] = true;
}
}
TestDoc.requires.loaded = {};
TestDoc.report = function() {
TestDoc.report.counter = 0;
print("1.."+TestDoc.plans);
for (var i = 0; i < TestDoc.results.length; i++) {
print(TestDoc.results[i]);
}
print("----------------------------------------");
if (TestDoc.fails == 0 && TestDoc.passes == TestDoc.plans) {
print("All tests successful.");
}
else {
print("Failed " + TestDoc.fails + "/" + TestDoc.plans + " tests, "+((TestDoc.plans == 0)? 0 : Math.round(TestDoc.passes/(TestDoc.passes+TestDoc.fails)*10000)/100)+"% okay. Planned to run "+TestDoc.plans+", did run "+(TestDoc.passes+TestDoc.fails)+".")
}
}
TestDoc.plan = function(n, message) {
TestDoc.plans += n;
TestDoc.record(new TestDoc.Result(null, message+" ("+n+" tests)"));
}
TestDoc.assertEquals = function(a, b, message) {
var result = (a == b);
if (!result) message += "\n#\n# " + a + " does not equal " + b + "\n#";
TestDoc.record(new TestDoc.Result(result, message));
}
TestDoc.assertNotEquals = function(a, b, message) {
var result = (a != b);
if (!result) message += "\n#\n# " + a + " equals " + b + "\n#";
TestDoc.record(new TestDoc.Result(result, message));
}
TestDoc.readFile = (function(){
// rhino
if (typeof readFile == "function") {
return function(url) {
var text = readFile(url);
return text || "";
}
}
// a web browser
else {
return function(url) {
var httpRequest;
if (window.XMLHttpRequest) { // Mozilla, Safari, etc
httpRequest = new XMLHttpRequest();
}
else if (window.ActiveXObject) { // IE
try {
httpRequest = new ActiveXObject("Msxml2.XMLHTTP");
}
catch (e) {
try {
httpRequest = new ActiveXObject("Microsoft.XMLHTTP");
}
catch (e) {
}
}
}
if (!httpRequest) { throw "Cannot create HTTP Request."; }
httpRequest.open('GET', url, false);
httpRequest.send('');
if (httpRequest.readyState == 4) {
if (httpRequest.status >= 400) {
throw "The HTTP Request returned an error code: "+httpRequest.status;
}
}
return httpRequest.responseText || "";
}
}
})();
| JavaScript |
// try: java -jar ../../jsrun.jar runner.js
load("TestDoc.js");
TestDoc.prove("../frame/Opt.js");
TestDoc.prove("../lib/JSDOC.js");
TestDoc.prove("../frame/String.js");
TestDoc.prove("../lib/JSDOC/DocTag.js");
TestDoc.prove("../lib/JSDOC/DocComment.js");
TestDoc.prove("../lib/JSDOC/TokenReader.js");
TestDoc.prove("../lib/JSDOC/Symbol.js");
TestDoc.report();
| JavaScript |
load("app/frame/Dumper.js");
function symbolize(opt) {
symbols = null;
JSDOC.JsDoc(opt);
symbols = JSDOC.JsDoc.symbolSet;
}
var testCases = [
function() {
symbolize({a:true, p:true, _: [SYS.pwd+"test/overview.js"]});
//print(Dumper.dump(symbols));
is('symbols.getSymbolByName("My Cool Library").name', 'My Cool Library', 'File overview can be found by alias.');
}
,
function() {
symbolize({_: [SYS.pwd+"test/name.js"]});
is('symbols.getSymbol("Response").name', "Response", 'Virtual class name is found.');
is('symbols.getSymbol("Response#text").alias', "Response#text", 'Virtual method name is found.');
is('symbols.getSymbol("Response#text").memberOf', "Response", 'Virtual method parent name is found.');
}
,
function() {
symbolize({a:true, p:true, _: [SYS.pwd+"test/prototype.js"]});
is('symbols.getSymbol("Article").name', "Article", 'Function set to constructor prototype with inner constructor name is found.');
is('symbols.getSymbol("Article").hasMethod("init")', true, 'The initializer method name of prototype function is correct.');
is('symbols.getSymbol("Article").hasMember("counter")', true, 'A static property set in the prototype definition is found.');
is('symbols.getSymbol("Article").hasMember("title")', true, 'An instance property set in the prototype is found.');
is('symbols.getSymbol("Article#title").isStatic', false, 'An instance property has isStatic set to false.');
is('symbols.getSymbol("Article.counter").name', "counter", 'A static property set in the initializer has the name set correctly.');
is('symbols.getSymbol("Article.counter").memberOf', "Article", 'A static property set in the initializer has the memberOf set correctly.');
is('symbols.getSymbol("Article.counter").isStatic', true, 'A static property set in the initializer has isStatic set to true.');
}
,
function() {
symbolize({a:true, _: [SYS.pwd+"test/prototype_oblit.js"]});
is('symbols.getSymbol("Article").name', "Article", 'Oblit set to constructor prototype name is found.');
is('typeof symbols.getSymbol("Article.prototype")', "undefined", 'The prototype oblit is not a symbol.');
is('symbols.getSymbol("Article#getTitle").name', "getTitle", 'The nonstatic method name of prototype oblit is correct.');
is('symbols.getSymbol("Article#getTitle").alias', "Article#getTitle", 'The alias of non-static method of prototype oblit is correct.');
is('symbols.getSymbol("Article#getTitle").isStatic', false, 'The isStatic of a nonstatic method of prototype oblit is correct.');
is('symbols.getSymbol("Article.getTitle").name', "getTitle", 'The static method name of prototype oblit is correct.');
is('symbols.getSymbol("Article.getTitle").isStatic', true, 'The isStatic of a static method of prototype oblit is correct.');
is('symbols.getSymbol("Article#getTitle").isa', "FUNCTION", 'The isa of non-static method of prototype oblit is correct.');
is('symbols.getSymbol("Article.getTitle").alias', "Article.getTitle", 'The alias of a static method of prototype oblit is correct.');
is('symbols.getSymbol("Article.getTitle").isa', "FUNCTION", 'The isa of static method of prototype oblit is correct.');
}
,
function() {
symbolize({a:true, p:true, _: [SYS.pwd+"test/prototype_oblit_constructor.js"]});
is('symbols.getSymbol("Article").name', "Article", 'Oblit set to constructor prototype with inner constructor name is found.');
is('symbols.getSymbol("Article#init").name', "init", 'The initializer method name of prototype oblit is correct.');
is('symbols.getSymbol("Article").hasMember("pages")', true, 'Property set by initializer method "this" is on the outer constructor.');
is('symbols.getSymbol("Article#Title").name', "Title", 'Name of the inner constructor name is found.');
is('symbols.getSymbol("Article#Title").memberOf', "Article", 'The memberOf of the inner constructor name is found.');
is('symbols.getSymbol("Article#Title").isa', "CONSTRUCTOR", 'The isa of the inner constructor name is constructor.');
is('symbols.getSymbol("Article#Title").hasMember("title")', true, 'A property set on the inner constructor "this" is on the inner constructor.');
}
,
function() {
symbolize({a:true, p:true, _: [SYS.pwd+"test/inner.js"]});
is('symbols.getSymbol("Outer").name', "Outer", 'Outer constructor prototype name is found.');
is('symbols.getSymbol("Outer").methods.length', 1, 'Inner function doesnt appear as a method of the outer.');
is('symbols.getSymbol("Outer").hasMethod("open")', true, 'Outer constructors methods arent affected by inner function.');
is('symbols.getSymbol("Outer-Inner").alias', "Outer-Inner", 'Alias of inner function is found.');
is('symbols.getSymbol("Outer-Inner").isa', "CONSTRUCTOR", 'isa of inner function constructor is found.');
is('symbols.getSymbol("Outer-Inner").memberOf', "Outer", 'The memberOf of inner function is found.');
is('symbols.getSymbol("Outer-Inner").name', "Inner", 'The name of inner function is found.');
is('symbols.getSymbol("Outer-Inner#name").name', "name", 'A member of the inner function constructor, attached to "this" is found on inner.');
is('symbols.getSymbol("Outer-Inner#name").memberOf', "Outer-Inner", 'The memberOf of an inner function member is found.');
}
,
function() {
symbolize({a:true, _: [SYS.pwd+"test/prototype_nested.js"]});
is('symbols.getSymbol("Word").name', "Word", 'Base constructor name is found.');
is('symbols.getSymbol("Word").hasMethod("reverse")', true, 'Base constructor method is found.');
is('symbols.getSymbol("Word").methods.length', 1, 'Base constructor has only one method.');
is('symbols.getSymbol("Word").memberOf', "", 'Base constructor memberOf is empty.');
is('symbols.getSymbol("Word#reverse").name', "reverse", 'Member of constructor prototype name is found.');
is('symbols.getSymbol("Word#reverse").memberOf', "Word", 'Member of constructor prototype memberOf is found.');
is('symbols.getSymbol("Word#reverse.utf8").name', "utf8", 'Member of constructor prototype method name is found.');
is('symbols.getSymbol("Word#reverse.utf8").memberOf', "Word#reverse", 'Static nested member memberOf is found.');
}
,
function() {
symbolize({a:true, _: [SYS.pwd+"test/namespace_nested.js"]});
is('symbols.getSymbol("ns1").name', "ns1", 'Base namespace name is found.');
is('symbols.getSymbol("ns1").memberOf', "", 'Base namespace memberOf is empty (its a constructor).');
is('symbols.getSymbol("ns1.ns2").name', "ns2", 'Nested namespace name is found.');
is('symbols.getSymbol("ns1.ns2").alias', "ns1.ns2", 'Nested namespace alias is found.');
is('symbols.getSymbol("ns1.ns2").memberOf', "ns1", 'Nested namespace memberOf is found.');
is('symbols.getSymbol("ns1.ns2.Function1").name', "Function1", 'Method of nested namespace name is found.');
is('symbols.getSymbol("ns1.ns2.Function1").memberOf', "ns1.ns2", 'Constructor of nested namespace memberOf is found.');
}
,
function() {
symbolize({a:true, p:true, _: [SYS.pwd+"test/functions_nested.js"]});
is('symbols.getSymbol("Zop").name', "Zop", 'Any constructor name is found.');
is('symbols.getSymbol("Zop").isa', "CONSTRUCTOR", 'It isa constructor.');
is('symbols.getSymbol("Zop").hasMethod("zap")', true, 'Its method name, set later, is in methods array.');
is('symbols.getSymbol("Foo").name', "Foo", 'The containing constructor name is found.');
is('symbols.getSymbol("Foo").hasMethod("methodOne")', true, 'Its method name is found.');
is('symbols.getSymbol("Foo").hasMethod("methodTwo")', true, 'Its second method name is found.');
is('symbols.getSymbol("Foo#methodOne").alias', "Foo#methodOne", 'A methods alias is found.');
is('symbols.getSymbol("Foo#methodOne").isStatic', false, 'A methods is not static.');
is('symbols.getSymbol("Bar").name', "Bar", 'A global function declared inside another function is found.');
is('symbols.getSymbol("Bar").isa', "FUNCTION", 'It isa function.');
is('symbols.getSymbol("Bar").memberOf', "_global_", 'It is global.');
is('symbols.getSymbol("Foo-inner").name', "inner", 'An inner functions name is found.');
is('symbols.getSymbol("Foo-inner").memberOf', "Foo", 'It is member of the outer function.');
is('symbols.getSymbol("Foo-inner").isInner', true, 'It is an inner function.');
}
,
function() {
symbolize({a:true, _: [SYS.pwd+"test/memberof_constructor.js"]});
is('symbols.getSymbol("Circle#Tangent").name', "Tangent", 'Constructor set on prototype using @member has correct name.');
is('symbols.getSymbol("Circle#Tangent").memberOf', "Circle", 'Constructor set on prototype using @member has correct memberOf.');
is('symbols.getSymbol("Circle#Tangent").alias', "Circle#Tangent", 'Constructor set on prototype using @member has correct alias.');
is('symbols.getSymbol("Circle#Tangent").isa', "CONSTRUCTOR", 'Constructor set on prototype using @member has correct isa.');
is('symbols.getSymbol("Circle#Tangent").isStatic', false, 'Constructor set on prototype using @member is not static.');
is('symbols.getSymbol("Circle#Tangent#getDiameter").name', "getDiameter", 'Method set on prototype using @member has correct name.');
is('symbols.getSymbol("Circle#Tangent#getDiameter").memberOf', "Circle#Tangent", 'Method set on prototype using @member has correct memberOf.');
is('symbols.getSymbol("Circle#Tangent#getDiameter").alias', "Circle#Tangent#getDiameter", 'Method set on prototype using @member has correct alias.');
is('symbols.getSymbol("Circle#Tangent#getDiameter").isa', "FUNCTION", 'Method set on prototype using @member has correct isa.');
is('symbols.getSymbol("Circle#Tangent#getDiameter").isStatic', false, 'Method set on prototype using @member is not static.');
}
,
function() {
symbolize({a:true, p: true, _: [SYS.pwd+"test/memberof.js"]});
is('symbols.getSymbol("pack.install").alias', "pack.install", 'Using @memberOf sets alias, when parent name is in memberOf tag.');
is('symbols.getSymbol("pack.install.overwrite").name', "install.overwrite", 'Using @memberOf sets name, even if the name is dotted.');
is('symbols.getSymbol("pack.install.overwrite").memberOf', "pack", 'Using @memberOf sets memberOf.');
is('symbols.getSymbol("pack.install.overwrite").isStatic', true, 'Using @memberOf with value not ending in octothorp sets isStatic to true.');
}
,
function() {
symbolize({a:true, p: true, _: [SYS.pwd+"test/memberof2.js"]});
is('symbols.getSymbol("Foo#bar").alias', "Foo#bar", 'An inner function can be documented as an instance method.');
is('symbols.getSymbol("Foo.zip").alias', "Foo.zip", 'An inner function can be documented as a static method.');
is('symbols.getSymbol("Foo.Fiz").alias', "Foo.Fiz", 'An inner function can be documented as a static constructor.');
is('symbols.getSymbol("Foo.Fiz#fipple").alias', "Foo.Fiz#fipple", 'An inner function can be documented as a static constructor with a method.');
is('symbols.getSymbol("Foo#blat").alias', "Foo#blat", 'An global function can be documented as an instance method.');
}
,
function() {
symbolize({a:true, p: true, _: [SYS.pwd+"test/memberof3.js"]});
is('symbols.getSymbol("Foo#bar").alias', "Foo#bar", 'A virtual field can be documented as an instance method.');
is('symbols.getSymbol("Foo2#bar").alias', "Foo2#bar", 'A virtual field with the same name can be documented as an instance method.');
}
,
function() {
symbolize({a:true, p:true, _: [SYS.pwd+"test/borrows.js"]});
is('symbols.getSymbol("Layout").name', "Layout", 'Constructor can be found.');
is('symbols.getSymbol("Layout").hasMethod("init")', true, 'Constructor method name can be found.');
is('symbols.getSymbol("Layout").hasMember("orientation")', true, 'Constructor property name can be found.');
is('symbols.getSymbol("Page").hasMethod("reset")', true, 'Second constructor method name can be found.');
is('symbols.getSymbol("Page").hasMember("orientation")', true, 'Second constructor borrowed property name can be found in properties.');
is('symbols.getSymbol("Page#orientation").memberOf', "Page", 'Second constructor borrowed property memberOf can be found.');
is('symbols.getSymbol("Page-getInnerElements").alias', "Page-getInnerElements", 'Can borrow an inner function and it is still inner.');
is('symbols.getSymbol("Page.units").alias', "Page.units", 'Can borrow a static function and it is still static.');
is('symbols.getSymbol("ThreeColumnPage#init").alias', "ThreeColumnPage#init", 'Third constructor method can be found even though method with same name is borrowed.');
is('symbols.getSymbol("ThreeColumnPage#reset").alias', "ThreeColumnPage#reset", 'Borrowed method can be found.');
is('symbols.getSymbol("ThreeColumnPage#orientation").alias', "ThreeColumnPage#orientation", 'Twice borrowed method can be found.');
}
,
function() {
symbolize({a:true, p:true, _: [SYS.pwd+"test/borrows2.js"]});
is('symbols.getSymbol("Foo").hasMethod("my_zop")', true, 'Borrowed method can be found.');
is('symbols.getSymbol("Bar").hasMethod("my_zip")', true, 'Second borrowed method can be found.');
}
,
function() {
symbolize({a:true, p:true, _: [SYS.pwd+"test/constructs.js"]});
is('symbols.getSymbol("Person").hasMethod("say")', true, 'The constructs tag creates a class that lends can add a method to.');
}
,
function() {
symbolize({a: true, _: [SYS.pwd+"test/augments.js", SYS.pwd+"test/augments2.js"]});
is('symbols.getSymbol("Page").augments[0]', "Layout", 'An augmented class can be found.');
is('symbols.getSymbol("Page#reset").alias', "Page#reset", 'Method of augmenter can be found.');
is('symbols.getSymbol("Page").hasMethod("Layout#init")', true, 'Method from augmented can be found.');
is('symbols.getSymbol("Page").hasMember("Layout#orientation")', true, 'Property from augmented can be found.');
is('symbols.getSymbol("Page").methods.length', 3, 'Methods of augmented class are included in methods array.');
is('symbols.getSymbol("ThreeColumnPage").augments[0]', "Page", 'The extends tag is a synonym for augments.');
is('symbols.getSymbol("ThreeColumnPage").hasMethod("ThreeColumnPage#init")', true, 'Local method overrides augmented method of same name.');
is('symbols.getSymbol("ThreeColumnPage").methods.length', 3, 'Local method count is right.');
is('symbols.getSymbol("NewsletterPage").augments[0]', "ThreeColumnPage", 'Can augment across file boundaries.');
is('symbols.getSymbol("NewsletterPage").augments.length', 2, 'Multiple augments are supported.');
is('symbols.getSymbol("NewsletterPage").inherits[0].alias', "Junkmail#annoy", 'Inherited method with augments.');
is('symbols.getSymbol("NewsletterPage").methods.length', 6, 'Methods of augmented class are included in methods array across files.');
is('symbols.getSymbol("NewsletterPage").properties.length', 1, 'Properties of augmented class are included in properties array across files.');
}
,
function() {
symbolize({a:true, _: [SYS.pwd+"test/static_this.js"]});
is('symbols.getSymbol("box.holder").name', "holder", 'Static namespace name can be found.');
is('symbols.getSymbol("box.holder.foo").name', "foo", 'Static namespace method name can be found.');
is('symbols.getSymbol("box.holder").isStatic', true, 'Static namespace method is static.');
is('symbols.getSymbol("box.holder.counter").name', "counter", 'Instance namespace property name set on "this" can be found.');
is('symbols.getSymbol("box.holder.counter").alias', "box.holder.counter", 'Instance namespace property alias set on "this" can be found.');
is('symbols.getSymbol("box.holder.counter").memberOf', "box.holder", 'Static namespace property memberOf set on "this" can be found.');
}
,
function() {
symbolize({a:true, p: true, _: [SYS.pwd+"test/lend.js"]});
is('symbols.getSymbol("Person").name', "Person", 'Class defined in lend comment is found.');
is('symbols.getSymbol("Person").hasMethod("initialize")', true, 'Lent instance method name can be found.');
is('symbols.getSymbol("Person").hasMethod("say")', true, 'Second instance method can be found.');
is('symbols.getSymbol("Person#sing").isStatic', false, 'Instance method is known to be not static.');
is('symbols.getSymbol("Person.getCount").name', "getCount", 'Static method name from second lend comment can be found.');
is('symbols.getSymbol("Person.getCount").isStatic', true, 'Static method from second lend comment is known to be static.');
is('LOG.warnings.filter(function($){if($.indexOf("notok") > -1) return $}).length', 1, 'A warning is emitted when lending to an undocumented parent.');
}
,
function() {
symbolize({a:true, _: [SYS.pwd+"test/param_inline.js"]});
is('symbols.getSymbol("Layout").params[0].type', "int", 'Inline param name is set.');
is('symbols.getSymbol("Layout").params[0].desc', "The number of columns.", 'Inline param desc is set from comment.');
is('symbols.getSymbol("Layout#getElement").params[0].name', "id", 'User defined param documentation takes precedence over parser defined.');
is('symbols.getSymbol("Layout#getElement").params[0].isOptional', true, 'Default for param is to not be optional.');
is('symbols.getSymbol("Layout#getElement").params[1].isOptional', false, 'Can mark a param as being optional.');
is('symbols.getSymbol("Layout#getElement").params[1].type', "number|string", 'Type of inline param doc can have multiple values.');
is('symbols.getSymbol("Layout#Canvas").params[0].type', "", 'Type can be not defined for some params.');
is('symbols.getSymbol("Layout#Canvas").params[2].type', "int", 'Type can be defined inline for only some params.');
is('symbols.getSymbol("Layout#rotate").params.length', 0, 'Docomments inside function sig is ignored without a param.');
is('symbols.getSymbol("Layout#init").params[2].type', "zoppler", 'Doc comment type overrides inline type for param with same name.');
}
,
function() {
symbolize({a: true, _: [SYS.pwd+"test/shared.js", SYS.pwd+"test/shared2.js"]});
is('symbols.getSymbol("Array#some").name', 'some', 'The name of a symbol in a shared section is found.');
is('symbols.getSymbol("Array#some").alias', 'Array#some', 'The alias of a symbol in a shared section is found.');
is('symbols.getSymbol("Array#some").desc', "Extension to builtin array.", 'A description can be shared.');
is('symbols.getSymbol("Array#filter").desc', "Extension to builtin array.\nChange every element of an array.", 'A shared description is appended.');
is('symbols.getSymbol("Queue").desc', "A first in, first out data structure.", 'A description is not shared when outside a shared section.');
is('symbols.getSymbol("Queue.rewind").alias', "Queue.rewind", 'Second shared tag can be started.');
is('symbols.getSymbol("startOver").alias', "startOver", 'Shared tag doesnt cross over files.');
}
,
function() {
symbolize({a: true, _: [SYS.pwd+"test/config.js"]});
is('symbols.getSymbol("Contact").params[0].name', 'person', 'The name of a param is found.');
is('symbols.getSymbol("Contact").params[1].name', 'person.name', 'The name of a param set with a dot name is found.');
is('symbols.getSymbol("Contact").params[2].name', 'person.age', 'The name of a second param set with a dot name is found.');
is('symbols.getSymbol("Contact").params[4].name', 'connection', 'The name of a param after config is found.');
is('symbols.getSymbol("Family").params[0].name', 'persons', 'Another name of a param is found.');
is('symbols.getSymbol("Family").params[1].name', 'persons.Father', 'The name of a param+config is found.');
is('symbols.getSymbol("Family").params[2].name', 'persons.Mother', 'The name of a second param+config is found.');
is('symbols.getSymbol("Family").params[3].name', 'persons.Children', 'The name of a third param+config is found.');
}
,
function() {
symbolize({a:true, p:true, _: [SYS.pwd+"test/ignore.js"]});
is('LOG.warnings.filter(function($){if($.indexOf("undocumented symbol Ignored") > -1) return $}).length', 1, 'A warning is emitted when documenting members of an ignored parent.');
}
,
function() {
symbolize({a:true, p:true, _: [SYS.pwd+"test/functions_anon.js"]});
is('symbols.getSymbol("a.b").alias', 'a.b', 'In anonymous constructor this is found to be the container object.');
is('symbols.getSymbol("a.f").alias', 'a.f', 'In anonymous constructor this can have a method.');
is('symbols.getSymbol("a.c").alias', 'a.c', 'In anonymous constructor method this is found to be the container object.');
is('symbols.getSymbol("g").alias', 'g', 'In anonymous function executed inline this is the global.');
is('symbols.getSymbol("bar2.p").alias', 'bar2.p', 'In named constructor executed inline this is the container object.');
is('symbols.getSymbol("module.pub").alias', 'module.pub', 'In parenthesized anonymous function executed inline function scoped variables arent documented.');
}
,
function() {
symbolize({a:true, p:true, _: [SYS.pwd+"test/oblit_anon.js"]});
is('symbols.getSymbol("opt").name', 'opt', 'Anonymous object properties are created.');
is('symbols.getSymbol("opt.conf.keep").alias', 'opt.conf.keep', 'Anonymous object first property is assigned to $anonymous.');
is('symbols.getSymbol("opt.conf.base").alias', 'opt.conf.base', 'Anonymous object second property is assigned to $anonymous.');
}
,
function() {
symbolize({a:true, p:true, _: [SYS.pwd+"test/params_optional.js"]});
is('symbols.getSymbol("Document").params.length', 3, 'Correct number of params are found when optional param syntax is used.');
is('symbols.getSymbol("Document").params[1].name', "id", 'Name of optional param is found.');
is('symbols.getSymbol("Document").params[1].isOptional', true, 'Optional param is marked isOptional.');
is('symbols.getSymbol("Document").params[2].name', "title", 'Name of optional param with default value is found.');
is('symbols.getSymbol("Document").params[2].isOptional', true, 'Optional param with default value is marked isOptional.');
is('symbols.getSymbol("Document").params[2].defaultValue', " This is untitled.", 'Optional param default value is found.');
}
,
function() {
symbolize({a:true, p:true, _: [SYS.pwd+"test/synonyms.js"]});
is('symbols.getSymbol("myObject.myFunc").type', 'function', 'Type can be set to function.');
}
,
function() {
symbolize({a:true, p:true, _: [SYS.pwd+"test/event.js"]});
is('symbols.getSymbol("Kitchen#event:cakeEaten").isEvent', true, 'Function with event prefix is an event.');
is('symbols.getSymbol("Kitchen#cakeEaten").isa', "FUNCTION", 'Function with same name as event isa function.');
}
,
function() {
symbolize({x:"js", a:true, _: [SYS.pwd+"test/scripts/"]});
is('JSDOC.JsDoc.srcFiles.length', 1, 'Only js files are scanned when -x=js.');
}
,
function() {
symbolize({x:"js", a:true, _: [SYS.pwd+"test/exports.js"]});
is('symbols.getSymbol("mxn.Map#doThings").name', 'doThings', 'Exports creates a documentation alias that can have methods.');
}
,
function() {
symbolize({p:true, a:true, _: [SYS.pwd+"test/module.js"]});
is('symbols.getSymbol("myProject.myModule.myPublicMethod").name', 'myPublicMethod', 'A function wrapped in parens can be recognized.');
is('symbols.getSymbol("myProject.myModule-myPrivateMethod").name', 'myPrivateMethod', 'A private method in the scope of a function wrapped in parens can be recognized.');
is('symbols.getSymbol("myProject.myModule-myPrivateVar").name', 'myPrivateVar', 'A private member in the scope of a function wrapped in parens can be recognized.');
}
];
//// run and print results
print(testrun(testCases));
| JavaScript |
/**
* @fileOverview
* A bootstrap script that creates some basic required objects
* for loading other scripts.
* @author Michael Mathews, micmath@gmail.com
* @version $Id: run.js 756 2009-01-07 21:32:58Z micmath $
*/
/**
* @namespace Keep track of any messages from the running script.
*/
LOG = {
warn: function(msg, e) {
if (JSDOC.opt.q) return;
if (e) msg = e.fileName+", line "+e.lineNumber+": "+msg;
msg = ">> WARNING: "+msg;
LOG.warnings.push(msg);
if (LOG.out) LOG.out.write(msg+"\n");
else print(msg);
},
inform: function(msg) {
if (JSDOC.opt.q) return;
msg = " > "+msg;
if (LOG.out) LOG.out.write(msg+"\n");
else if (typeof LOG.verbose != "undefined" && LOG.verbose) print(msg);
}
};
LOG.warnings = [];
LOG.verbose = false
LOG.out = undefined;
/**
* @class Manipulate a filepath.
*/
function FilePath(absPath, separator) {
this.slash = separator || "/";
this.root = this.slash;
this.path = [];
this.file = "";
var parts = absPath.split(/[\\\/]/);
if (parts) {
if (parts.length) this.root = parts.shift() + this.slash;
if (parts.length) this.file = parts.pop()
if (parts.length) this.path = parts;
}
this.path = this.resolvePath();
}
/** Collapse any dot-dot or dot items in a filepath. */
FilePath.prototype.resolvePath = function() {
var resolvedPath = [];
for (var i = 0; i < this.path.length; i++) {
if (this.path[i] == "..") resolvedPath.pop();
else if (this.path[i] != ".") resolvedPath.push(this.path[i]);
}
return resolvedPath;
}
/** Trim off the filename. */
FilePath.prototype.toDir = function() {
if (this.file) this.file = "";
return this;
}
/** Go up a directory. */
FilePath.prototype.upDir = function() {
this.toDir();
if (this.path.length) this.path.pop();
return this;
}
FilePath.prototype.toString = function() {
return this.root
+ this.path.join(this.slash)
+ ((this.path.length > 0)? this.slash : "")
+ this.file;
}
/**
* Turn a path into just the name of the file.
*/
FilePath.fileName = function(path) {
var nameStart = Math.max(path.lastIndexOf("/")+1, path.lastIndexOf("\\")+1, 0);
return path.substring(nameStart);
}
/**
* Get the extension of a filename
*/
FilePath.fileExtension = function(filename) {
return filename.split(".").pop().toLowerCase();
};
/**
* Turn a path into just the directory part.
*/
FilePath.dir = function(path) {
var nameStart = Math.max(path.lastIndexOf("/")+1, path.lastIndexOf("\\")+1, 0);
return path.substring(0, nameStart-1);
}
importClass(java.lang.System);
/**
* @namespace A collection of information about your system.
*/
SYS = {
/**
* Information about your operating system: arch, name, version.
* @type string
*/
os: [
new String(System.getProperty("os.arch")),
new String(System.getProperty("os.name")),
new String(System.getProperty("os.version"))
].join(", "),
/**
* Which way does your slash lean.
* @type string
*/
slash: System.getProperty("file.separator")||"/",
/**
* The path to the working directory where you ran java.
* @type string
*/
userDir: new String(System.getProperty("user.dir")),
/**
* Where is Java's home folder.
* @type string
*/
javaHome: new String(System.getProperty("java.home")),
/**
* The absolute path to the directory containing this script.
* @type string
*/
pwd: undefined
};
// jsrun appends an argument, with the path to here.
if (arguments[arguments.length-1].match(/^-j=(.+)/)) {
if (RegExp.$1.charAt(0) == SYS.slash || RegExp.$1.charAt(1) == ":") { // absolute path to here
SYS.pwd = new FilePath(RegExp.$1).toDir().toString();
}
else { // relative path to here
SYS.pwd = new FilePath(SYS.userDir + SYS.slash + RegExp.$1).toDir().toString();
}
arguments.pop();
}
else {
print("The run.js script requires you use jsrun.jar.");
quit();
}
// shortcut
var File = Packages.java.io.File;
/**
* @namespace A collection of functions that deal with reading a writing to disk.
*/
IO = {
/**
* Create a new file in the given directory, with the given name and contents.
*/
saveFile: function(/**string*/ outDir, /**string*/ fileName, /**string*/ content) {
var out = new Packages.java.io.PrintWriter(
new Packages.java.io.OutputStreamWriter(
new Packages.java.io.FileOutputStream(outDir+SYS.slash+fileName),
IO.encoding
)
);
out.write(content);
out.flush();
out.close();
},
/**
* @type string
*/
readFile: function(/**string*/ path) {
if (!IO.exists(path)) {
throw "File doesn't exist there: "+path;
}
return readFile(path, IO.encoding);
},
/**
* @param inFile
* @param outDir
* @param [fileName=The original filename]
*/
copyFile: function(/**string*/ inFile, /**string*/ outDir, /**string*/ fileName) {
if (fileName == null) fileName = FilePath.fileName(inFile);
var inFile = new File(inFile);
var outFile = new File(outDir+SYS.slash+fileName);
var bis = new Packages.java.io.BufferedInputStream(new Packages.java.io.FileInputStream(inFile), 4096);
var bos = new Packages.java.io.BufferedOutputStream(new Packages.java.io.FileOutputStream(outFile), 4096);
var theChar;
while ((theChar = bis.read()) != -1) {
bos.write(theChar);
}
bos.close();
bis.close();
},
/**
* Creates a series of nested directories.
*/
mkPath: function(/**Array*/ path) {
if (path.constructor != Array) path = path.split(/[\\\/]/);
var make = "";
for (var i = 0, l = path.length; i < l; i++) {
make += path[i] + SYS.slash;
if (! IO.exists(make)) {
IO.makeDir(make);
}
}
},
/**
* Creates a directory at the given path.
*/
makeDir: function(/**string*/ path) {
(new File(path)).mkdir();
},
/**
* @type string[]
* @param dir The starting directory to look in.
* @param [recurse=1] How many levels deep to scan.
* @returns An array of all the paths to files in the given dir.
*/
ls: function(/**string*/ dir, /**number*/ recurse, _allFiles, _path) {
if (_path === undefined) { // initially
var _allFiles = [];
var _path = [dir];
}
if (_path.length == 0) return _allFiles;
if (recurse === undefined) recurse = 1;
dir = new File(dir);
if (!dir.directory) return [String(dir)];
var files = dir.list();
for (var f = 0; f < files.length; f++) {
var file = String(files[f]);
if (file.match(/^\.[^\.\/\\]/)) continue; // skip dot files
if ((new File(_path.join(SYS.slash)+SYS.slash+file)).list()) { // it's a directory
_path.push(file);
if (_path.length-1 < recurse) IO.ls(_path.join(SYS.slash), recurse, _allFiles, _path);
_path.pop();
}
else {
_allFiles.push((_path.join(SYS.slash)+SYS.slash+file).replace(SYS.slash+SYS.slash, SYS.slash));
}
}
return _allFiles;
},
/**
* @type boolean
*/
exists: function(/**string*/ path) {
file = new File(path);
if (file.isDirectory()){
return true;
}
if (!file.exists()){
return false;
}
if (!file.canRead()){
return false;
}
return true;
},
/**
*
*/
open: function(/**string*/ path, /**string*/ append) {
var append = true;
var outFile = new File(path);
var out = new Packages.java.io.PrintWriter(
new Packages.java.io.OutputStreamWriter(
new Packages.java.io.FileOutputStream(outFile, append),
IO.encoding
)
);
return out;
},
/**
* Sets {@link IO.encoding}.
* Encoding is used when reading and writing text to files,
* and in the meta tags of HTML output.
*/
setEncoding: function(/**string*/ encoding) {
if (/ISO-8859-([0-9]+)/i.test(encoding)) {
IO.encoding = "ISO8859_"+RegExp.$1;
}
else {
IO.encoding = encoding;
}
},
/**
* @default "utf-8"
* @private
*/
encoding: "utf-8",
/**
* Load the given script.
*/
include: function(relativePath) {
load(SYS.pwd+relativePath);
},
/**
* Loads all scripts from the given directory path.
*/
includeDir: function(path) {
if (!path) return;
for (var lib = IO.ls(SYS.pwd+path), i = 0; i < lib.length; i++)
if (/\.js$/i.test(lib[i])) load(lib[i]);
}
}
// now run the application
IO.include("frame.js");
IO.include("main.js");
main();
| JavaScript |
/**
* @version $Id: main.js 818 2009-11-08 14:51:41Z micmath $
*/
function main() {
IO.include("lib/JSDOC.js");
IO.includeDir("plugins/");
// process the options
// the -c option: options are defined in a configuration file
if (JSDOC.opt.c) {
eval("JSDOC.conf = " + IO.readFile(JSDOC.opt.c));
LOG.inform("Using configuration file at '"+JSDOC.opt.c+"'.");
for (var c in JSDOC.conf) {
if (c !== "D" && !defined(JSDOC.opt[c])) { // commandline overrules config file
JSDOC.opt[c] = JSDOC.conf[c];
}
}
if (typeof JSDOC.conf["_"] != "undefined") {
JSDOC.opt["_"] = JSDOC.opt["_"].concat(JSDOC.conf["_"]);
}
LOG.inform("With configuration: ");
for (var o in JSDOC.opt) {
LOG.inform(" "+o+": "+JSDOC.opt[o]);
}
}
// be verbose
if (JSDOC.opt.v) LOG.verbose = true;
// send log messages to a file
if (JSDOC.opt.o) LOG.out = IO.open(JSDOC.opt.o);
// run the unit tests
if (JSDOC.opt.T) {
LOG.inform("JsDoc Toolkit running in test mode at "+new Date()+".");
IO.include("frame/Testrun.js");
IO.include("test.js");
}
else {
// a template must be defined and must be a directory path
if (!JSDOC.opt.t && System.getProperty("jsdoc.template.dir")) {
JSDOC.opt.t = System.getProperty("jsdoc.template.dir");
}
if (JSDOC.opt.t && SYS.slash != JSDOC.opt.t.slice(-1)) {
JSDOC.opt.t += SYS.slash;
}
// verbose messages about the options we were given
LOG.inform("JsDoc Toolkit main() running at "+new Date()+".");
LOG.inform("With options: ");
for (var o in JSDOC.opt) {
LOG.inform(" "+o+": "+JSDOC.opt[o]);
}
// initialize and build a symbolSet from your code
JSDOC.JsDoc();
// debugger's option: dump the entire symbolSet produced from your code
if (JSDOC.opt.Z) {
LOG.warn("So you want to see the data structure, eh? This might hang if you have circular refs...");
IO.include("frame/Dumper.js");
var symbols = JSDOC.JsDoc.symbolSet.toArray();
for (var i = 0, l = symbols.length; i < l; i++) {
var symbol = symbols[i];
print("// symbol: " + symbol.alias);
print(symbol.serialize());
}
}
else {
if (typeof JSDOC.opt.t != "undefined") {
try {
// a file named "publish.js" must exist in the template directory
load(JSDOC.opt.t+"publish.js");
// and must define a function named "publish"
if (!publish) {
LOG.warn("No publish() function is defined in that template so nothing to do.");
}
else {
// which will be called with the symbolSet produced from your code
publish(JSDOC.JsDoc.symbolSet);
}
}
catch(e) {
LOG.warn("Sorry, that doesn't seem to be a valid template: "+JSDOC.opt.t+"publish.js : "+e);
}
}
else {
LOG.warn("No template given. Might as well read the usage notes.");
JSDOC.usage();
}
}
}
// notify of any warnings
if (!JSDOC.opt.q && LOG.warnings.length) {
print(LOG.warnings.length+" warning"+(LOG.warnings.length != 1? "s":"")+".");
}
// stop sending log messages to a file
if (LOG.out) {
LOG.out.flush();
LOG.out.close();
}
} | JavaScript |
JSDOC.PluginManager.registerPlugin(
"JSDOC.publishSrcHilite",
{
onPublishSrc: function(src) {
if (src.path in JsHilite.cache) {
return; // already generated src code
}
else JsHilite.cache[src.path] = true;
try {
var sourceCode = IO.readFile(src.path);
}
catch(e) {
print(e.message);
quit();
}
var hiliter = new JsHilite(sourceCode, src.charset);
src.hilited = hiliter.hilite();
}
}
);
function JsHilite(src, charset) {
var tr = new JSDOC.TokenReader();
tr.keepComments = true;
tr.keepDocs = true;
tr.keepWhite = true;
this.tokens = tr.tokenize(new JSDOC.TextStream(src));
// TODO is redefining toString() the best way?
JSDOC.Token.prototype.toString = function() {
return "<span class=\""+this.type+"\">"+this.data.replace(/</g, "<")+"</span>";
}
if (!charset) charset = "utf-8";
this.header = '<html><head><meta http-equiv="content-type" content="text/html; charset='+charset+'"> '+
"<style>\n\
.KEYW {color: #933;}\n\
.COMM {color: #bbb; font-style: italic;}\n\
.NUMB {color: #393;}\n\
.STRN {color: #393;}\n\
.REGX {color: #339;}\n\
.line {border-right: 1px dotted #666; color: #666; font-style: normal;}\n\
</style></head><body><pre>";
this.footer = "</pre></body></html>";
this.showLinenumbers = true;
}
JsHilite.cache = {};
JsHilite.prototype.hilite = function() {
var hilited = this.tokens.join("");
var line = 1;
if (this.showLinenumbers) hilited = hilited.replace(/(^|\n)/g, function(m){return m+"<span class='line'>"+((line<10)? " ":"")+((line<100)? " ":"")+(line++)+"</span> "});
return this.header+hilited+this.footer;
} | JavaScript |
JSDOC.PluginManager.registerPlugin(
"JSDOC.commentSrcJson",
{
onDocCommentSrc: function(comment) {
var json;
if (/^\s*@json\b/.test(comment)) {
comment.src = new String(comment.src).replace("@json", "");
eval("json = "+comment.src);
var tagged = "";
for (var i in json) {
var tag = json[i];
// todo handle cases where tag is an object
tagged += "@"+i+" "+tag+"\n";
}
comment.src = tagged;
}
}
}
); | JavaScript |
JSDOC.PluginManager.registerPlugin(
"JSDOC.tagParamConfig",
{
onDocCommentTags: function(comment) {
var currentParam = null;
var tags = comment.tags;
for (var i = 0, l = tags.length; i < l; i++) {
if (tags[i].title == "param") {
if (tags[i].name.indexOf(".") == -1) {
currentParam = i;
}
}
else if (tags[i].title == "config") {
tags[i].title = "param";
if (currentParam == null) {
tags[i].name = "arguments"+"."+tags[i].name;
}
else if (tags[i].name.indexOf(tags[currentParam].name+".") != 0) {
tags[i].name = tags[currentParam].name+"."+tags[i].name;
}
currentParam != null
//tags[currentParam].properties.push(tags[i]);
}
else {
currentParam = null;
}
}
}
}
);
| JavaScript |
JSDOC.PluginManager.registerPlugin(
"JSDOC.symbolLink",
{
onSymbolLink: function(link) {
// modify link.linkPath (the href part of the link)
// or link.linkText (the text displayed)
// or link.linkInner (the #name part of the link)
}
}
); | JavaScript |
JSDOC.PluginManager.registerPlugin(
"JSDOC.functionCall",
{
onFunctionCall: function(functionCall) {
if (functionCall.name == "dojo.define" && functionCall.arg1) {
functionCall.doc = "/** @lends "+eval(functionCall.arg1)+".prototype */";
}
}
}
); | JavaScript |
JSDOC.PluginManager.registerPlugin(
"JSDOC.frameworkPrototype",
{
onPrototypeClassCreate: function(classCreator) {
var desc = "";
if (classCreator.comment) {
desc = classCreator.comment;
}
var insert = desc+"/** @name "+classCreator.name+"\n@constructor\n@scope "+classCreator.name+".prototype */"
insert = insert.replace(/\*\/\/\*\*/g, "\n");
/*DEBUG*///print("insert is "+insert);
classCreator.addComment.data = insert;
}
}
);
| JavaScript |
JSDOC.PluginManager.registerPlugin(
"JSDOC.tagSynonyms",
{
onDocCommentSrc: function(comment) {
comment.src = comment.src.replace(/@methodOf\b/i, "@function\n@memberOf");
comment.src = comment.src.replace(/@fieldOf\b/i, "@field\n@memberOf");
},
onDocCommentTags: function(comment) {
for (var i = 0, l = comment.tags.length; i < l; i++) {
var title = comment.tags[i].title.toLowerCase();
var syn;
if ((syn = JSDOC.tagSynonyms.synonyms["="+title])) {
comment.tags[i].title = syn;
}
}
}
}
);
new Namespace(
"JSDOC.tagSynonyms",
function() {
JSDOC.tagSynonyms.synonyms = {
"=member": "memberOf",
"=memberof": "memberOf",
"=description": "desc",
"=exception": "throws",
"=argument": "param",
"=returns": "return",
"=classdescription": "class",
"=fileoverview": "overview",
"=extends": "augments",
"=base": "augments",
"=projectdescription": "overview",
"=classdescription": "class",
"=link": "see",
"=borrows": "inherits",
"=scope": "lends",
"=construct": "constructor"
}
}
); | JavaScript |
/** Handle the creation of HTML links to documented symbols.
@constructor
*/
function Link() {
this.alias = "";
this.src = "";
this.file = "";
this.text = "";
this.innerName = "";
this.classLink = false;
this.targetName = "";
this.target = function(targetName) {
if (defined(targetName)) this.targetName = targetName;
return this;
}
this.inner = function(inner) {
if (defined(inner)) this.innerName = inner;
return this;
}
this.withText = function(text) {
if (defined(text)) this.text = text;
return this;
}
this.toSrc = function(filename) {
if (defined(filename)) this.src = filename;
return this;
}
this.toSymbol = function(alias) {
if (defined(alias)) this.alias = new String(alias);
return this;
}
this.toClass = function(alias) {
this.classLink = true;
return this.toSymbol(alias);
}
this.toFile = function(file) {
if (defined(file)) this.file = file;
return this;
}
this.toString = function() {
var linkString;
var thisLink = this;
if (this.alias) {
linkString = this.alias.replace(/(^|[^a-z$0-9_#.:^-])([|a-z$0-9_#.:^-]+)($|[^a-z$0-9_#.:^-])/i,
function(match, prematch, symbolName, postmatch) {
var symbolNames = symbolName.split("|");
var links = [];
for (var i = 0, l = symbolNames.length; i < l; i++) {
thisLink.alias = symbolNames[i];
links.push(thisLink._makeSymbolLink(symbolNames[i]));
}
return prematch+links.join("|")+postmatch;
}
);
}
else if (this.src) {
linkString = thisLink._makeSrcLink(this.src);
}
else if (this.file) {
linkString = thisLink._makeFileLink(this.file);
}
return linkString;
}
}
/** prefixed for hashes */
Link.hashPrefix = "";
/** Appended to the front of relative link paths. */
Link.base = "";
Link.symbolNameToLinkName = function(symbol) {
var linker = "",
ns = "";
if (symbol.isStatic) linker = ".";
else if (symbol.isInner) linker = "-";
if (symbol.isEvent && !/^event:/.test(symbol.name)) {
ns = "event:";
}
return Link.hashPrefix+linker+ns+symbol.name;
}
Link.getSymbol= function(alias) {
var symbol= Link.symbolSet.getSymbol(alias);
if (symbol)
return symbol;
if ('#'!==alias.charAt(0) || !Link.currentSymbol)
return null;
// resolve relative name
var container= Link.currentSymbol;
while (container)
{
symbol= Link.symbolSet.getSymbol(container.alias + alias);
if (symbol)
return symbol;
// No superclass
if (!container.augments.length)
return null;
container= Link.symbolSet.getSymbol(container.augments[0].desc);
}
return null;
}
/** Create a link to another symbol. */
Link.prototype._makeSymbolLink = function(alias) {
var linkBase = Link.base+publish.conf.symbolsDir;
var linkTo = Link.getSymbol(alias);
var linkPath;
var target = (this.targetName)? " target=\""+this.targetName+"\"" : "";
// if there is no symbol by that name just return the name unaltered
if (!linkTo)
return this.text || alias;
// it's a symbol in another file
else {
if (!linkTo.is("CONSTRUCTOR") && !linkTo.isNamespace) { // it's a method or property
linkPath= (Link.filemap) ? Link.filemap[linkTo.memberOf] :
escape(linkTo.memberOf) || "_global_";
linkPath += publish.conf.ext + "#" + Link.symbolNameToLinkName(linkTo);
}
else {
linkPath = (Link.filemap)? Link.filemap[linkTo.alias] : escape(linkTo.alias);
linkPath += publish.conf.ext;// + (this.classLink? "":"#" + Link.hashPrefix + "constructor");
}
linkPath = linkBase + linkPath
}
var linkText= this.text || alias;
var link = {linkPath: linkPath, linkText: linkText, linkInner: (this.innerName? "#"+this.innerName : "")};
if (typeof JSDOC.PluginManager != "undefined") {
JSDOC.PluginManager.run("onSymbolLink", link);
}
return "<a href=\""+link.linkPath+link.linkInner+"\""+target+">"+link.linkText+"</a>";
}
/** Create a link to a source file. */
Link.prototype._makeSrcLink = function(srcFilePath) {
var target = (this.targetName)? " target=\""+this.targetName+"\"" : "";
// transform filepath into a filename
var srcFile = srcFilePath.replace(/\.\.?[\\\/]/g, "").replace(/[:\\\/]/g, "_");
var outFilePath = Link.base + publish.conf.srcDir + srcFile + publish.conf.ext;
if (!this.text) this.text = FilePath.fileName(srcFilePath);
return "<a href=\""+outFilePath+"\""+target+">"+this.text+"</a>";
}
/** Create a link to a source file. */
Link.prototype._makeFileLink = function(filePath) {
var target = (this.targetName)? " target=\""+this.targetName+"\"" : "";
var outFilePath = Link.base + filePath;
if (!this.text) this.text = filePath;
return "<a href=\""+outFilePath+"\""+target+">"+this.text+"</a>";
} | JavaScript |
/** @namespace */
Opt = {
/**
* Get commandline option values.
* @param {Array} args Commandline arguments. Like ["-a=xml", "-b", "--class=new", "--debug"]
* @param {object} optNames Map short names to long names. Like {a:"accept", b:"backtrace", c:"class", d:"debug"}.
* @return {object} Short names and values. Like {a:"xml", b:true, c:"new", d:true}
*/
get: function(args, optNames) {
var opt = {"_": []}; // the unnamed option allows multiple values
for (var i = 0; i < args.length; i++) {
var arg = new String(args[i]);
var name;
var value;
if (arg.charAt(0) == "-") {
if (arg.charAt(1) == "-") { // it's a longname like --foo
arg = arg.substring(2);
var m = arg.split("=");
name = m.shift();
value = m.shift();
if (typeof value == "undefined") value = true;
for (var n in optNames) { // convert it to a shortname
if (name == optNames[n]) {
name = n;
}
}
}
else { // it's a shortname like -f
arg = arg.substring(1);
var m = arg.split("=");
name = m.shift();
value = m.shift();
if (typeof value == "undefined") value = true;
for (var n in optNames) { // find the matching key
if (name == n || name+'[]' == n) {
name = n;
break;
}
}
}
if (name.match(/(.+)\[\]$/)) { // it's an array type like n[]
name = RegExp.$1;
if (!opt[name]) opt[name] = [];
}
if (opt[name] && opt[name].push) {
opt[name].push(value);
}
else {
opt[name] = value;
}
}
else { // not associated with any optname
opt._.push(args[i]);
}
}
return opt;
}
}
/*t:
plan(11, "Testing Opt.");
is(
typeof Opt,
"object",
"Opt is an object."
);
is(
typeof Opt.get,
"function",
"Opt.get is a function."
);
var optNames = {a:"accept", b:"backtrace", c:"class", d:"debug", "e[]":"exceptions"};
var t_options = Opt.get(["-a=xml", "-b", "--class=new", "--debug", "-e=one", "-e=two", "foo", "bar"], optNames);
is(
t_options.a,
"xml",
"an option defined with a short name can be accessed by its short name."
);
is(
t_options.b,
true,
"an option defined with a short name and no value are true."
);
is(
t_options.c,
"new",
"an option defined with a long name can be accessed by its short name."
);
is(
t_options.d,
true,
"an option defined with a long name and no value are true."
);
is(
typeof t_options.e,
"object",
"an option that can accept multiple values is defined."
);
is(
t_options.e.length,
2,
"an option that can accept multiple values can have more than one value."
);
is(
t_options.e[1],
"two",
"an option that can accept multiple values can be accessed as an array."
);
is(
typeof t_options._,
"object",
"the property '_' is defined for unnamed options."
);
is(
t_options._[0],
"foo",
"the property '_' can be accessed as an array."
);
*/ | JavaScript |
/**
* @fileOverview
* @name JsTestrun
* @author Michael Mathews micmath@gmail.com
* @url $HeadURL: https://jsdoc-toolkit.googlecode.com/svn/tags/jsdoc_toolkit-2.4.0/jsdoc-toolkit/app/frame/Testrun.js $
* @revision $Id: Testrun.js 418 2008-01-15 21:40:33Z micmath $
* @license <a href="http://en.wikipedia.org/wiki/MIT_License">X11/MIT License</a>
* (See the accompanying README file for full details.)
*/
/**
Yet another unit testing tool for JavaScript.
@author Michael Mathews <a href="mailto:micmath@gmail.com">micmath@gmail.com</a>
@param {object} testCases Properties are testcase names, values are functions to execute as tests.
*/
function testrun(testCases) {
var ran = 0;
for (t in testCases) {
var result = testCases[t]();
ran++;
}
return testrun.reportOut+"-------------------------------\n"+((testrun.fails>0)? ":( Failed "+testrun.fails+"/" : ":) Passed all ")+testrun.count+" test"+((testrun.count == 1)? "":"s")+".\n";
}
testrun.count = 0;
testrun.current = null;
testrun.passes = 0;
testrun.fails = 0;
testrun.reportOut = "";
/** @private */
testrun.report = function(text) {
testrun.reportOut += text+"\n";
}
/**
Check if test evaluates to true.
@param {string} test To be evaluated.
@param {string} message Optional. To be displayed in the report.
@return {boolean} True if the string test evaluates to true.
*/
ok = function(test, message) {
testrun.count++;
var result;
try {
result = eval(test);
if (result) {
testrun.passes++;
testrun.report(" OK "+testrun.count+" - "+((message != null)? message : ""));
}
else {
testrun.fails++;
testrun.report("NOT OK "+testrun.count+" - "+((message != null)? message : ""));
}
}
catch(e) {
testrun.fails++
testrun.report("NOT OK "+testrun.count+" - "+((message != null)? message : ""));
}
}
/**
Check if test is same as expected.
@param {string} test To be evaluated.
@param {string} expected
@param {string} message Optional. To be displayed in the report.
@return {boolean} True if (test == expected). Note that the comparison is not a strict equality check.
*/
is = function(test, expected, message) {
testrun.count++;
var result;
try {
result = eval(test);
if (result == expected) {
testrun.passes++
testrun.report(" OK "+testrun.count+" - "+((message != null)? message : ""));
}
else {
testrun.fails++
testrun.report("NOT OK "+testrun.count+" - "+((message != null)? message : ""));
testrun.report("expected: "+expected);
testrun.report(" got: "+result);
}
}
catch(e) {
testrun.fails++
testrun.report("NOT OK "+testrun.count+" - "+((message != null)? message : ""));
testrun.report("expected: "+expected);
testrun.report(" got: "+result);}
}
/**
Check if test matches pattern.
@param {string} test To be evaluated.
@param {string} pattern Used to create a RegExp.
@param {string} message Optional. To be displayed in the report.
@return {boolean} True if test matches pattern.
*/
like = function(test, pattern, message) {
testrun.count++;
var result;
try {
result = eval(test);
var rgx = new RegExp(pattern);
if (rgx.test(result)) {
testrun.passes++
testrun.report(" OK "+testrun.count+" - "+((message != null)? message : ""));
}
else {
testrun.fails++
testrun.report("NOT OK "+testrun.count+" - "+((message != null)? message : ""));
testrun.report(" this: "+result);
testrun.report("is not like: "+pattern);
}
}
catch(e) {
testrun.fails++
testrun.report("NOT OK "+testrun.count+" - "+((message != null)? message : ""));
}
} | JavaScript |
/**
@constructor
@example
var _index = new Hash();
_index.set("a", "apple");
_index.set("b", "blue");
_index.set("c", "coffee");
for (var p = _index.first(); p; p = _index.next()) {
print(p.key+" is for "+p.value);
}
*/
var Hash = function() {
this._map = {};
this._keys = [];
this._vals = [];
this.reset();
}
Hash.prototype.set = function(k, v) {
if (k != "") {
this._keys.push(k);
this._map["="+k] = this._vals.length;
this._vals.push(v);
}
}
Hash.prototype.replace = function(k, k2, v) {
if (k == k2) return;
var offset = this._map["="+k];
this._keys[offset] = k2;
if (typeof v != "undefined") this._vals[offset] = v;
this._map["="+k2] = offset;
delete(this._map["="+k]);
}
Hash.prototype.drop = function(k) {
if (k != "") {
var offset = this._map["="+k];
this._keys.splice(offset, 1);
this._vals.splice(offset, 1);
delete(this._map["="+k]);
for (var p in this._map) {
if (this._map[p] >= offset) this._map[p]--;
}
if (this._cursor >= offset && this._cursor > 0) this._cursor--;
}
}
Hash.prototype.get = function(k) {
if (k != "") {
return this._vals[this._map["="+k]];
}
}
Hash.prototype.keys = function() {
return this._keys;
}
Hash.prototype.hasKey = function(k) {
if (k != "") {
return (typeof this._map["="+k] != "undefined");
}
}
Hash.prototype.values = function() {
return this._vals;
}
Hash.prototype.reset = function() {
this._cursor = 0;
}
Hash.prototype.first = function() {
this.reset();
return this.next();
}
Hash.prototype.next = function() {
if (this._cursor++ < this._keys.length)
return {key: this._keys[this._cursor-1], value: this._vals[this._cursor-1]};
} | JavaScript |
_global_ = this;
function Namespace(name, f) {
var n = name.split(".");
for (var o = _global_, i = 0, l = n.length; i < l; i++) {
o = o[n[i]] = o[n[i]] || {};
}
if (f) f();
} | JavaScript |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.