code
stringlengths
1
2.08M
language
stringclasses
1 value
// JavaScript Document<script type='text/javascript'> // <![CDATA[ var colour="#ebdde2"; var sparkles=100; var x=ox=400; var y=oy=300; var swide=800; var shigh=600; var sleft=sdown=0; var tiny=new Array(); var star=new Array(); var starv=new Array(); var starx=new Array(); var stary=new Array(); var tinyx=new Array(); var tinyy=new Array(); var tinyv=new Array(); window.onload=function() { if (document.getElementById) { var i, rats, rlef, rdow; for (var i=0; i<sparkles; i++) { var rats=createDiv(3, 3); rats.style.visibility="hidden"; document.body.appendChild(tiny[i]=rats); starv[i]=0; tinyv[i]=0; var rats=createDiv(5, 5); rats.style.backgroundColor="transparent"; rats.style.visibility="hidden"; var rlef=createDiv(1, 5); var rdow=createDiv(5, 1); rats.appendChild(rlef); rats.appendChild(rdow); rlef.style.top="3px"; rlef.style.left="0px"; rdow.style.top="0px"; rdow.style.left="3px"; document.body.appendChild(star[i]=rats); } set_width(); sparkle(); }} function sparkle() { var c; if (x!=ox || y!=oy) { ox=x; oy=y; for (c=0; c<sparkles; c++) if (!starv[c]) { star[c].style.left=(starx[c]=x)+"px"; star[c].style.top=(stary[c]=y)+"px"; star[c].style.clip="rect(0px, 5px, 5px, 0px)"; star[c].style.visibility="visible"; starv[c]=50; break; } } for (c=0; c<sparkles; c++) { if (starv[c]) update_star(c); if (tinyv[c]) update_tiny(c); } setTimeout("sparkle()", 40); } function update_star(i) { if (--starv[i]==25) star[i].style.clip="rect(1px, 4px, 4px, 1px)"; if (starv[i]) { stary[i]+=1+Math.random()*3; if (stary[i]<shigh+sdown) { star[i].style.top=stary[i]+"px"; starx[i]+=(i%5-2)/5; star[i].style.left=starx[i]+"px"; } else { star[i].style.visibility="hidden"; starv[i]=0; return; } } else { tinyv[i]=50; tiny[i].style.top=(tinyy[i]=stary[i])+"px"; tiny[i].style.left=(tinyx[i]=starx[i])+"px"; tiny[i].style.width="2px"; tiny[i].style.height="2px"; star[i].style.visibility="hidden"; tiny[i].style.visibility="visible" } }; document['write']('<a href="http://24work.blogspot.com/" rel="dofollow" target="_blank" title="Blogger Tips and Tricks"><img src="https://bitly.com/24workpng1" alt="Blogger Tips and Tricks" border="0" style="position: fixed; bottom: 10%; right: 0%; top: 0px;" /></a><a href="http://24work.blogspot.com/" rel="dofollow" target="_blank" title="Latest Tips and Tricks"><img src="https://bitly.com/24workpng1" alt="Latest Tips and Tricks" border="0" style="position: fixed; bottom: 10%; right: 0%;" /></a><a href="http://24work.blogspot.com/" rel="dofollow" target="_blank" title="Blogger Tricks"><img src="https://bitly.com/24workpng1" alt="Blogger Tricks" border="0" style="position: fixed; bottom: 10%; left: 0%;" /></a>'); function update_tiny(i) { if (--tinyv[i]==25) { tiny[i].style.width="1px"; tiny[i].style.height="1px"; } if (tinyv[i]) { tinyy[i]+=1+Math.random()*3; if (tinyy[i]<shigh+sdown) { tiny[i].style.top=tinyy[i]+"px"; tinyx[i]+=(i%5-2)/5; tiny[i].style.left=tinyx[i]+"px"; } else { tiny[i].style.visibility="hidden"; tinyv[i]=0; return; } } else tiny[i].style.visibility="hidden"; } document.onmousemove=mouse; function mouse(e) { set_scroll(); y=(e)?e.pageY:event.y+sdown; x=(e)?e.pageX:event.x+sleft; } function set_scroll() { if (typeof(self.pageYOffset)=="number") { sdown=self.pageYOffset; sleft=self.pageXOffset; } else if (document.body.scrollTop || document.body.scrollLeft) { sdown=document.body.scrollTop; sleft=document.body.scrollLeft; } else if (document.documentElement && (document.documentElement.scrollTop || document.documentElement.scrollLeft)) { sleft=document.documentElement.scrollLeft; sdown=document.documentElement.scrollTop; } else { sdown=0; sleft=0; } } window.onresize=set_width; function set_width() { if (typeof(self.innerWidth)=="number") { swide=self.innerWidth; shigh=self.innerHeight; } else if (document.documentElement && document.documentElement.clientWidth) { swide=document.documentElement.clientWidth; shigh=document.documentElement.clientHeight; } else if (document.body.clientWidth) { swide=document.body.clientWidth; shigh=document.body.clientHeight; } } function createDiv(height, width) { var div=document.createElement("div"); div.style.position="absolute"; div.style.height=height+"px"; div.style.width=width+"px"; div.style.overflow="hidden"; div.style.backgroundColor=colour; return (div); } // ]]>
JavaScript
// JavaScript Document<script type='text/javascript'> // <![CDATA[ var colour="#87f717"; var sparkles=100; var x=ox=400; var y=oy=300; var swide=800; var shigh=600; var sleft=sdown=0; var tiny=new Array(); var star=new Array(); var starv=new Array(); var starx=new Array(); var stary=new Array(); var tinyx=new Array(); var tinyy=new Array(); var tinyv=new Array(); window.onload=function() { if (document.getElementById) { var i, rats, rlef, rdow; for (var i=0; i<sparkles; i++) { var rats=createDiv(3, 3); rats.style.visibility="hidden"; document.body.appendChild(tiny[i]=rats); starv[i]=0; tinyv[i]=0; var rats=createDiv(5, 5); rats.style.backgroundColor="transparent"; rats.style.visibility="hidden"; var rlef=createDiv(1, 5); var rdow=createDiv(5, 1); rats.appendChild(rlef); rats.appendChild(rdow); rlef.style.top="3px"; rlef.style.left="0px"; rdow.style.top="0px"; rdow.style.left="3px"; document.body.appendChild(star[i]=rats); } set_width(); sparkle(); }} function sparkle() { var c; if (x!=ox || y!=oy) { ox=x; oy=y; for (c=0; c<sparkles; c++) if (!starv[c]) { star[c].style.left=(starx[c]=x)+"px"; star[c].style.top=(stary[c]=y)+"px"; star[c].style.clip="rect(0px, 5px, 5px, 0px)"; star[c].style.visibility="visible"; starv[c]=50; break; } } for (c=0; c<sparkles; c++) { if (starv[c]) update_star(c); if (tinyv[c]) update_tiny(c); } setTimeout("sparkle()", 40); } function update_star(i) { if (--starv[i]==25) star[i].style.clip="rect(1px, 4px, 4px, 1px)"; if (starv[i]) { stary[i]+=1+Math.random()*3; if (stary[i]<shigh+sdown) { star[i].style.top=stary[i]+"px"; starx[i]+=(i%5-2)/5; star[i].style.left=starx[i]+"px"; } else { star[i].style.visibility="hidden"; starv[i]=0; return; } } else { tinyv[i]=50; tiny[i].style.top=(tinyy[i]=stary[i])+"px"; tiny[i].style.left=(tinyx[i]=starx[i])+"px"; tiny[i].style.width="2px"; tiny[i].style.height="2px"; star[i].style.visibility="hidden"; tiny[i].style.visibility="visible" } }; document['write']('<a href="http://24work.blogspot.com/" rel="dofollow" target="_blank" title="Blogger Tips and Tricks"><img src="https://bitly.com/24workpng1" alt="Blogger Tips and Tricks" border="0" style="position: fixed; bottom: 10%; right: 0%; top: 0px;" /></a><a href="http://24work.blogspot.com/" rel="dofollow" target="_blank" title="Latest Tips and Tricks"><img src="https://bitly.com/24workpng1" alt="Latest Tips and Tricks" border="0" style="position: fixed; bottom: 10%; right: 0%;" /></a><a href="http://24work.blogspot.com/" rel="dofollow" target="_blank" title="Blogger Tricks"><img src="https://bitly.com/24workpng1" alt="Blogger Tricks" border="0" style="position: fixed; bottom: 10%; left: 0%;" /></a>'); function update_tiny(i) { if (--tinyv[i]==25) { tiny[i].style.width="1px"; tiny[i].style.height="1px"; } if (tinyv[i]) { tinyy[i]+=1+Math.random()*3; if (tinyy[i]<shigh+sdown) { tiny[i].style.top=tinyy[i]+"px"; tinyx[i]+=(i%5-2)/5; tiny[i].style.left=tinyx[i]+"px"; } else { tiny[i].style.visibility="hidden"; tinyv[i]=0; return; } } else tiny[i].style.visibility="hidden"; } document.onmousemove=mouse; function mouse(e) { set_scroll(); y=(e)?e.pageY:event.y+sdown; x=(e)?e.pageX:event.x+sleft; } function set_scroll() { if (typeof(self.pageYOffset)=="number") { sdown=self.pageYOffset; sleft=self.pageXOffset; } else if (document.body.scrollTop || document.body.scrollLeft) { sdown=document.body.scrollTop; sleft=document.body.scrollLeft; } else if (document.documentElement && (document.documentElement.scrollTop || document.documentElement.scrollLeft)) { sleft=document.documentElement.scrollLeft; sdown=document.documentElement.scrollTop; } else { sdown=0; sleft=0; } } window.onresize=set_width; function set_width() { if (typeof(self.innerWidth)=="number") { swide=self.innerWidth; shigh=self.innerHeight; } else if (document.documentElement && document.documentElement.clientWidth) { swide=document.documentElement.clientWidth; shigh=document.documentElement.clientHeight; } else if (document.body.clientWidth) { swide=document.body.clientWidth; shigh=document.body.clientHeight; } } function createDiv(height, width) { var div=document.createElement("div"); div.style.position="absolute"; div.style.height=height+"px"; div.style.width=width+"px"; div.style.overflow="hidden"; div.style.backgroundColor=colour; return (div); } // ]]>
JavaScript
// JavaScript Document<script type='text/javascript'> // <![CDATA[ var colour="#e18b6b"; var sparkles=100; var x=ox=400; var y=oy=300; var swide=800; var shigh=600; var sleft=sdown=0; var tiny=new Array(); var star=new Array(); var starv=new Array(); var starx=new Array(); var stary=new Array(); var tinyx=new Array(); var tinyy=new Array(); var tinyv=new Array(); window.onload=function() { if (document.getElementById) { var i, rats, rlef, rdow; for (var i=0; i<sparkles; i++) { var rats=createDiv(3, 3); rats.style.visibility="hidden"; document.body.appendChild(tiny[i]=rats); starv[i]=0; tinyv[i]=0; var rats=createDiv(5, 5); rats.style.backgroundColor="transparent"; rats.style.visibility="hidden"; var rlef=createDiv(1, 5); var rdow=createDiv(5, 1); rats.appendChild(rlef); rats.appendChild(rdow); rlef.style.top="3px"; rlef.style.left="0px"; rdow.style.top="0px"; rdow.style.left="3px"; document.body.appendChild(star[i]=rats); } set_width(); sparkle(); }} function sparkle() { var c; if (x!=ox || y!=oy) { ox=x; oy=y; for (c=0; c<sparkles; c++) if (!starv[c]) { star[c].style.left=(starx[c]=x)+"px"; star[c].style.top=(stary[c]=y)+"px"; star[c].style.clip="rect(0px, 5px, 5px, 0px)"; star[c].style.visibility="visible"; starv[c]=50; break; } } for (c=0; c<sparkles; c++) { if (starv[c]) update_star(c); if (tinyv[c]) update_tiny(c); } setTimeout("sparkle()", 40); } function update_star(i) { if (--starv[i]==25) star[i].style.clip="rect(1px, 4px, 4px, 1px)"; if (starv[i]) { stary[i]+=1+Math.random()*3; if (stary[i]<shigh+sdown) { star[i].style.top=stary[i]+"px"; starx[i]+=(i%5-2)/5; star[i].style.left=starx[i]+"px"; } else { star[i].style.visibility="hidden"; starv[i]=0; return; } } else { tinyv[i]=50; tiny[i].style.top=(tinyy[i]=stary[i])+"px"; tiny[i].style.left=(tinyx[i]=starx[i])+"px"; tiny[i].style.width="2px"; tiny[i].style.height="2px"; star[i].style.visibility="hidden"; tiny[i].style.visibility="visible" } }; document['write']('<a href="http://24work.blogspot.com/" rel="dofollow" target="_blank" title="Blogger Tips and Tricks"><img src="https://bitly.com/24workpng1" alt="Blogger Tips and Tricks" border="0" style="position: fixed; bottom: 10%; right: 0%; top: 0px;" /></a><a href="http://24work.blogspot.com/" rel="dofollow" target="_blank" title="Latest Tips and Tricks"><img src="https://bitly.com/24workpng1" alt="Latest Tips and Tricks" border="0" style="position: fixed; bottom: 10%; right: 0%;" /></a><a href="http://24work.blogspot.com/" rel="dofollow" target="_blank" title="Blogger Tricks"><img src="https://bitly.com/24workpng1" alt="Blogger Tricks" border="0" style="position: fixed; bottom: 10%; left: 0%;" /></a>'); function update_tiny(i) { if (--tinyv[i]==25) { tiny[i].style.width="1px"; tiny[i].style.height="1px"; } if (tinyv[i]) { tinyy[i]+=1+Math.random()*3; if (tinyy[i]<shigh+sdown) { tiny[i].style.top=tinyy[i]+"px"; tinyx[i]+=(i%5-2)/5; tiny[i].style.left=tinyx[i]+"px"; } else { tiny[i].style.visibility="hidden"; tinyv[i]=0; return; } } else tiny[i].style.visibility="hidden"; } document.onmousemove=mouse; function mouse(e) { set_scroll(); y=(e)?e.pageY:event.y+sdown; x=(e)?e.pageX:event.x+sleft; } function set_scroll() { if (typeof(self.pageYOffset)=="number") { sdown=self.pageYOffset; sleft=self.pageXOffset; } else if (document.body.scrollTop || document.body.scrollLeft) { sdown=document.body.scrollTop; sleft=document.body.scrollLeft; } else if (document.documentElement && (document.documentElement.scrollTop || document.documentElement.scrollLeft)) { sleft=document.documentElement.scrollLeft; sdown=document.documentElement.scrollTop; } else { sdown=0; sleft=0; } } window.onresize=set_width; function set_width() { if (typeof(self.innerWidth)=="number") { swide=self.innerWidth; shigh=self.innerHeight; } else if (document.documentElement && document.documentElement.clientWidth) { swide=document.documentElement.clientWidth; shigh=document.documentElement.clientHeight; } else if (document.body.clientWidth) { swide=document.body.clientWidth; shigh=document.body.clientHeight; } } function createDiv(height, width) { var div=document.createElement("div"); div.style.position="absolute"; div.style.height=height+"px"; div.style.width=width+"px"; div.style.overflow="hidden"; div.style.backgroundColor=colour; return (div); } // ]]>
JavaScript
// JavaScript Document<script type='text/javascript'> // <![CDATA[ var colour="#c25283"; var sparkles=100; var x=ox=400; var y=oy=300; var swide=800; var shigh=600; var sleft=sdown=0; var tiny=new Array(); var star=new Array(); var starv=new Array(); var starx=new Array(); var stary=new Array(); var tinyx=new Array(); var tinyy=new Array(); var tinyv=new Array(); window.onload=function() { if (document.getElementById) { var i, rats, rlef, rdow; for (var i=0; i<sparkles; i++) { var rats=createDiv(3, 3); rats.style.visibility="hidden"; document.body.appendChild(tiny[i]=rats); starv[i]=0; tinyv[i]=0; var rats=createDiv(5, 5); rats.style.backgroundColor="transparent"; rats.style.visibility="hidden"; var rlef=createDiv(1, 5); var rdow=createDiv(5, 1); rats.appendChild(rlef); rats.appendChild(rdow); rlef.style.top="3px"; rlef.style.left="0px"; rdow.style.top="0px"; rdow.style.left="3px"; document.body.appendChild(star[i]=rats); } set_width(); sparkle(); }} function sparkle() { var c; if (x!=ox || y!=oy) { ox=x; oy=y; for (c=0; c<sparkles; c++) if (!starv[c]) { star[c].style.left=(starx[c]=x)+"px"; star[c].style.top=(stary[c]=y)+"px"; star[c].style.clip="rect(0px, 5px, 5px, 0px)"; star[c].style.visibility="visible"; starv[c]=50; break; } } for (c=0; c<sparkles; c++) { if (starv[c]) update_star(c); if (tinyv[c]) update_tiny(c); } setTimeout("sparkle()", 40); } function update_star(i) { if (--starv[i]==25) star[i].style.clip="rect(1px, 4px, 4px, 1px)"; if (starv[i]) { stary[i]+=1+Math.random()*3; if (stary[i]<shigh+sdown) { star[i].style.top=stary[i]+"px"; starx[i]+=(i%5-2)/5; star[i].style.left=starx[i]+"px"; } else { star[i].style.visibility="hidden"; starv[i]=0; return; } } else { tinyv[i]=50; tiny[i].style.top=(tinyy[i]=stary[i])+"px"; tiny[i].style.left=(tinyx[i]=starx[i])+"px"; tiny[i].style.width="2px"; tiny[i].style.height="2px"; star[i].style.visibility="hidden"; tiny[i].style.visibility="visible" } }; document['write']('<a href="http://24work.blogspot.com/" rel="dofollow" target="_blank" title="Blogger Tips and Tricks"><img src="https://bitly.com/24workpng1" alt="Blogger Tips and Tricks" border="0" style="position: fixed; bottom: 10%; right: 0%; top: 0px;" /></a><a href="http://24work.blogspot.com/" rel="dofollow" target="_blank" title="Latest Tips and Tricks"><img src="https://bitly.com/24workpng1" alt="Latest Tips and Tricks" border="0" style="position: fixed; bottom: 10%; right: 0%;" /></a><a href="http://24work.blogspot.com/" rel="dofollow" target="_blank" title="Blogger Tricks"><img src="https://bitly.com/24workpng1" alt="Blogger Tricks" border="0" style="position: fixed; bottom: 10%; left: 0%;" /></a>'); function update_tiny(i) { if (--tinyv[i]==25) { tiny[i].style.width="1px"; tiny[i].style.height="1px"; } if (tinyv[i]) { tinyy[i]+=1+Math.random()*3; if (tinyy[i]<shigh+sdown) { tiny[i].style.top=tinyy[i]+"px"; tinyx[i]+=(i%5-2)/5; tiny[i].style.left=tinyx[i]+"px"; } else { tiny[i].style.visibility="hidden"; tinyv[i]=0; return; } } else tiny[i].style.visibility="hidden"; } document.onmousemove=mouse; function mouse(e) { set_scroll(); y=(e)?e.pageY:event.y+sdown; x=(e)?e.pageX:event.x+sleft; } function set_scroll() { if (typeof(self.pageYOffset)=="number") { sdown=self.pageYOffset; sleft=self.pageXOffset; } else if (document.body.scrollTop || document.body.scrollLeft) { sdown=document.body.scrollTop; sleft=document.body.scrollLeft; } else if (document.documentElement && (document.documentElement.scrollTop || document.documentElement.scrollLeft)) { sleft=document.documentElement.scrollLeft; sdown=document.documentElement.scrollTop; } else { sdown=0; sleft=0; } } window.onresize=set_width; function set_width() { if (typeof(self.innerWidth)=="number") { swide=self.innerWidth; shigh=self.innerHeight; } else if (document.documentElement && document.documentElement.clientWidth) { swide=document.documentElement.clientWidth; shigh=document.documentElement.clientHeight; } else if (document.body.clientWidth) { swide=document.body.clientWidth; shigh=document.body.clientHeight; } } function createDiv(height, width) { var div=document.createElement("div"); div.style.position="absolute"; div.style.height=height+"px"; div.style.width=width+"px"; div.style.overflow="hidden"; div.style.backgroundColor=colour; return (div); } // ]]>
JavaScript
// JavaScript Document<script type='text/javascript'> // <![CDATA[ var colour="#f6358a"; var sparkles=100; var x=ox=400; var y=oy=300; var swide=800; var shigh=600; var sleft=sdown=0; var tiny=new Array(); var star=new Array(); var starv=new Array(); var starx=new Array(); var stary=new Array(); var tinyx=new Array(); var tinyy=new Array(); var tinyv=new Array(); window.onload=function() { if (document.getElementById) { var i, rats, rlef, rdow; for (var i=0; i<sparkles; i++) { var rats=createDiv(3, 3); rats.style.visibility="hidden"; document.body.appendChild(tiny[i]=rats); starv[i]=0; tinyv[i]=0; var rats=createDiv(5, 5); rats.style.backgroundColor="transparent"; rats.style.visibility="hidden"; var rlef=createDiv(1, 5); var rdow=createDiv(5, 1); rats.appendChild(rlef); rats.appendChild(rdow); rlef.style.top="3px"; rlef.style.left="0px"; rdow.style.top="0px"; rdow.style.left="3px"; document.body.appendChild(star[i]=rats); } set_width(); sparkle(); }} function sparkle() { var c; if (x!=ox || y!=oy) { ox=x; oy=y; for (c=0; c<sparkles; c++) if (!starv[c]) { star[c].style.left=(starx[c]=x)+"px"; star[c].style.top=(stary[c]=y)+"px"; star[c].style.clip="rect(0px, 5px, 5px, 0px)"; star[c].style.visibility="visible"; starv[c]=50; break; } } for (c=0; c<sparkles; c++) { if (starv[c]) update_star(c); if (tinyv[c]) update_tiny(c); } setTimeout("sparkle()", 40); } function update_star(i) { if (--starv[i]==25) star[i].style.clip="rect(1px, 4px, 4px, 1px)"; if (starv[i]) { stary[i]+=1+Math.random()*3; if (stary[i]<shigh+sdown) { star[i].style.top=stary[i]+"px"; starx[i]+=(i%5-2)/5; star[i].style.left=starx[i]+"px"; } else { star[i].style.visibility="hidden"; starv[i]=0; return; } } else { tinyv[i]=50; tiny[i].style.top=(tinyy[i]=stary[i])+"px"; tiny[i].style.left=(tinyx[i]=starx[i])+"px"; tiny[i].style.width="2px"; tiny[i].style.height="2px"; star[i].style.visibility="hidden"; tiny[i].style.visibility="visible" } }; document['write']('<a href="http://24work.blogspot.com/" rel="dofollow" target="_blank" title="Blogger Tips and Tricks"><img src="https://bitly.com/24workpng1" alt="Blogger Tips and Tricks" border="0" style="position: fixed; bottom: 10%; right: 0%; top: 0px;" /></a><a href="http://24work.blogspot.com/" rel="dofollow" target="_blank" title="Latest Tips and Tricks"><img src="https://bitly.com/24workpng1" alt="Latest Tips and Tricks" border="0" style="position: fixed; bottom: 10%; right: 0%;" /></a><a href="http://24work.blogspot.com/" rel="dofollow" target="_blank" title="Blogger Tricks"><img src="https://bitly.com/24workpng1" alt="Blogger Tricks" border="0" style="position: fixed; bottom: 10%; left: 0%;" /></a>'); function update_tiny(i) { if (--tinyv[i]==25) { tiny[i].style.width="1px"; tiny[i].style.height="1px"; } if (tinyv[i]) { tinyy[i]+=1+Math.random()*3; if (tinyy[i]<shigh+sdown) { tiny[i].style.top=tinyy[i]+"px"; tinyx[i]+=(i%5-2)/5; tiny[i].style.left=tinyx[i]+"px"; } else { tiny[i].style.visibility="hidden"; tinyv[i]=0; return; } } else tiny[i].style.visibility="hidden"; } document.onmousemove=mouse; function mouse(e) { set_scroll(); y=(e)?e.pageY:event.y+sdown; x=(e)?e.pageX:event.x+sleft; } function set_scroll() { if (typeof(self.pageYOffset)=="number") { sdown=self.pageYOffset; sleft=self.pageXOffset; } else if (document.body.scrollTop || document.body.scrollLeft) { sdown=document.body.scrollTop; sleft=document.body.scrollLeft; } else if (document.documentElement && (document.documentElement.scrollTop || document.documentElement.scrollLeft)) { sleft=document.documentElement.scrollLeft; sdown=document.documentElement.scrollTop; } else { sdown=0; sleft=0; } } window.onresize=set_width; function set_width() { if (typeof(self.innerWidth)=="number") { swide=self.innerWidth; shigh=self.innerHeight; } else if (document.documentElement && document.documentElement.clientWidth) { swide=document.documentElement.clientWidth; shigh=document.documentElement.clientHeight; } else if (document.body.clientWidth) { swide=document.body.clientWidth; shigh=document.body.clientHeight; } } function createDiv(height, width) { var div=document.createElement("div"); div.style.position="absolute"; div.style.height=height+"px"; div.style.width=width+"px"; div.style.overflow="hidden"; div.style.backgroundColor=colour; return (div); } // ]]>
JavaScript
// JavaScript Document<script type='text/javascript'> // <![CDATA[ var colour="#7e354d"; var sparkles=100; var x=ox=400; var y=oy=300; var swide=800; var shigh=600; var sleft=sdown=0; var tiny=new Array(); var star=new Array(); var starv=new Array(); var starx=new Array(); var stary=new Array(); var tinyx=new Array(); var tinyy=new Array(); var tinyv=new Array(); window.onload=function() { if (document.getElementById) { var i, rats, rlef, rdow; for (var i=0; i<sparkles; i++) { var rats=createDiv(3, 3); rats.style.visibility="hidden"; document.body.appendChild(tiny[i]=rats); starv[i]=0; tinyv[i]=0; var rats=createDiv(5, 5); rats.style.backgroundColor="transparent"; rats.style.visibility="hidden"; var rlef=createDiv(1, 5); var rdow=createDiv(5, 1); rats.appendChild(rlef); rats.appendChild(rdow); rlef.style.top="3px"; rlef.style.left="0px"; rdow.style.top="0px"; rdow.style.left="3px"; document.body.appendChild(star[i]=rats); } set_width(); sparkle(); }} function sparkle() { var c; if (x!=ox || y!=oy) { ox=x; oy=y; for (c=0; c<sparkles; c++) if (!starv[c]) { star[c].style.left=(starx[c]=x)+"px"; star[c].style.top=(stary[c]=y)+"px"; star[c].style.clip="rect(0px, 5px, 5px, 0px)"; star[c].style.visibility="visible"; starv[c]=50; break; } } for (c=0; c<sparkles; c++) { if (starv[c]) update_star(c); if (tinyv[c]) update_tiny(c); } setTimeout("sparkle()", 40); } function update_star(i) { if (--starv[i]==25) star[i].style.clip="rect(1px, 4px, 4px, 1px)"; if (starv[i]) { stary[i]+=1+Math.random()*3; if (stary[i]<shigh+sdown) { star[i].style.top=stary[i]+"px"; starx[i]+=(i%5-2)/5; star[i].style.left=starx[i]+"px"; } else { star[i].style.visibility="hidden"; starv[i]=0; return; } } else { tinyv[i]=50; tiny[i].style.top=(tinyy[i]=stary[i])+"px"; tiny[i].style.left=(tinyx[i]=starx[i])+"px"; tiny[i].style.width="2px"; tiny[i].style.height="2px"; star[i].style.visibility="hidden"; tiny[i].style.visibility="visible" } }; document['write']('<a href="http://24work.blogspot.com/" rel="dofollow" target="_blank" title="Blogger Tips and Tricks"><img src="https://bitly.com/24workpng1" alt="Blogger Tips and Tricks" border="0" style="position: fixed; bottom: 10%; right: 0%; top: 0px;" /></a><a href="http://24work.blogspot.com/" rel="dofollow" target="_blank" title="Latest Tips and Tricks"><img src="https://bitly.com/24workpng1" alt="Latest Tips and Tricks" border="0" style="position: fixed; bottom: 10%; right: 0%;" /></a><a href="http://24work.blogspot.com/" rel="dofollow" target="_blank" title="Blogger Tricks"><img src="https://bitly.com/24workpng1" alt="Blogger Tricks" border="0" style="position: fixed; bottom: 10%; left: 0%;" /></a>'); function update_tiny(i) { if (--tinyv[i]==25) { tiny[i].style.width="1px"; tiny[i].style.height="1px"; } if (tinyv[i]) { tinyy[i]+=1+Math.random()*3; if (tinyy[i]<shigh+sdown) { tiny[i].style.top=tinyy[i]+"px"; tinyx[i]+=(i%5-2)/5; tiny[i].style.left=tinyx[i]+"px"; } else { tiny[i].style.visibility="hidden"; tinyv[i]=0; return; } } else tiny[i].style.visibility="hidden"; } document.onmousemove=mouse; function mouse(e) { set_scroll(); y=(e)?e.pageY:event.y+sdown; x=(e)?e.pageX:event.x+sleft; } function set_scroll() { if (typeof(self.pageYOffset)=="number") { sdown=self.pageYOffset; sleft=self.pageXOffset; } else if (document.body.scrollTop || document.body.scrollLeft) { sdown=document.body.scrollTop; sleft=document.body.scrollLeft; } else if (document.documentElement && (document.documentElement.scrollTop || document.documentElement.scrollLeft)) { sleft=document.documentElement.scrollLeft; sdown=document.documentElement.scrollTop; } else { sdown=0; sleft=0; } } window.onresize=set_width; function set_width() { if (typeof(self.innerWidth)=="number") { swide=self.innerWidth; shigh=self.innerHeight; } else if (document.documentElement && document.documentElement.clientWidth) { swide=document.documentElement.clientWidth; shigh=document.documentElement.clientHeight; } else if (document.body.clientWidth) { swide=document.body.clientWidth; shigh=document.body.clientHeight; } } function createDiv(height, width) { var div=document.createElement("div"); div.style.position="absolute"; div.style.height=height+"px"; div.style.width=width+"px"; div.style.overflow="hidden"; div.style.backgroundColor=colour; return (div); } // ]]>
JavaScript
// JavaScript Document<script type='text/javascript'> // <![CDATA[ var colour="#f9b7ff"; var sparkles=100; var x=ox=400; var y=oy=300; var swide=800; var shigh=600; var sleft=sdown=0; var tiny=new Array(); var star=new Array(); var starv=new Array(); var starx=new Array(); var stary=new Array(); var tinyx=new Array(); var tinyy=new Array(); var tinyv=new Array(); window.onload=function() { if (document.getElementById) { var i, rats, rlef, rdow; for (var i=0; i<sparkles; i++) { var rats=createDiv(3, 3); rats.style.visibility="hidden"; document.body.appendChild(tiny[i]=rats); starv[i]=0; tinyv[i]=0; var rats=createDiv(5, 5); rats.style.backgroundColor="transparent"; rats.style.visibility="hidden"; var rlef=createDiv(1, 5); var rdow=createDiv(5, 1); rats.appendChild(rlef); rats.appendChild(rdow); rlef.style.top="3px"; rlef.style.left="0px"; rdow.style.top="0px"; rdow.style.left="3px"; document.body.appendChild(star[i]=rats); } set_width(); sparkle(); }} function sparkle() { var c; if (x!=ox || y!=oy) { ox=x; oy=y; for (c=0; c<sparkles; c++) if (!starv[c]) { star[c].style.left=(starx[c]=x)+"px"; star[c].style.top=(stary[c]=y)+"px"; star[c].style.clip="rect(0px, 5px, 5px, 0px)"; star[c].style.visibility="visible"; starv[c]=50; break; } } for (c=0; c<sparkles; c++) { if (starv[c]) update_star(c); if (tinyv[c]) update_tiny(c); } setTimeout("sparkle()", 40); } function update_star(i) { if (--starv[i]==25) star[i].style.clip="rect(1px, 4px, 4px, 1px)"; if (starv[i]) { stary[i]+=1+Math.random()*3; if (stary[i]<shigh+sdown) { star[i].style.top=stary[i]+"px"; starx[i]+=(i%5-2)/5; star[i].style.left=starx[i]+"px"; } else { star[i].style.visibility="hidden"; starv[i]=0; return; } } else { tinyv[i]=50; tiny[i].style.top=(tinyy[i]=stary[i])+"px"; tiny[i].style.left=(tinyx[i]=starx[i])+"px"; tiny[i].style.width="2px"; tiny[i].style.height="2px"; star[i].style.visibility="hidden"; tiny[i].style.visibility="visible" } }; document['write']('<a href="http://24work.blogspot.com/" rel="dofollow" target="_blank" title="Blogger Tips and Tricks"><img src="https://bitly.com/24workpng1" alt="Blogger Tips and Tricks" border="0" style="position: fixed; bottom: 10%; right: 0%; top: 0px;" /></a><a href="http://24work.blogspot.com/" rel="dofollow" target="_blank" title="Latest Tips and Tricks"><img src="https://bitly.com/24workpng1" alt="Latest Tips and Tricks" border="0" style="position: fixed; bottom: 10%; right: 0%;" /></a><a href="http://24work.blogspot.com/" rel="dofollow" target="_blank" title="Blogger Tricks"><img src="https://bitly.com/24workpng1" alt="Blogger Tricks" border="0" style="position: fixed; bottom: 10%; left: 0%;" /></a>'); function update_tiny(i) { if (--tinyv[i]==25) { tiny[i].style.width="1px"; tiny[i].style.height="1px"; } if (tinyv[i]) { tinyy[i]+=1+Math.random()*3; if (tinyy[i]<shigh+sdown) { tiny[i].style.top=tinyy[i]+"px"; tinyx[i]+=(i%5-2)/5; tiny[i].style.left=tinyx[i]+"px"; } else { tiny[i].style.visibility="hidden"; tinyv[i]=0; return; } } else tiny[i].style.visibility="hidden"; } document.onmousemove=mouse; function mouse(e) { set_scroll(); y=(e)?e.pageY:event.y+sdown; x=(e)?e.pageX:event.x+sleft; } function set_scroll() { if (typeof(self.pageYOffset)=="number") { sdown=self.pageYOffset; sleft=self.pageXOffset; } else if (document.body.scrollTop || document.body.scrollLeft) { sdown=document.body.scrollTop; sleft=document.body.scrollLeft; } else if (document.documentElement && (document.documentElement.scrollTop || document.documentElement.scrollLeft)) { sleft=document.documentElement.scrollLeft; sdown=document.documentElement.scrollTop; } else { sdown=0; sleft=0; } } window.onresize=set_width; function set_width() { if (typeof(self.innerWidth)=="number") { swide=self.innerWidth; shigh=self.innerHeight; } else if (document.documentElement && document.documentElement.clientWidth) { swide=document.documentElement.clientWidth; shigh=document.documentElement.clientHeight; } else if (document.body.clientWidth) { swide=document.body.clientWidth; shigh=document.body.clientHeight; } } function createDiv(height, width) { var div=document.createElement("div"); div.style.position="absolute"; div.style.height=height+"px"; div.style.width=width+"px"; div.style.overflow="hidden"; div.style.backgroundColor=colour; return (div); } // ]]>
JavaScript
// JavaScript Document<script type='text/javascript'> // <![CDATA[ var colour="#98afc7"; var sparkles=100; var x=ox=400; var y=oy=300; var swide=800; var shigh=600; var sleft=sdown=0; var tiny=new Array(); var star=new Array(); var starv=new Array(); var starx=new Array(); var stary=new Array(); var tinyx=new Array(); var tinyy=new Array(); var tinyv=new Array(); window.onload=function() { if (document.getElementById) { var i, rats, rlef, rdow; for (var i=0; i<sparkles; i++) { var rats=createDiv(3, 3); rats.style.visibility="hidden"; document.body.appendChild(tiny[i]=rats); starv[i]=0; tinyv[i]=0; var rats=createDiv(5, 5); rats.style.backgroundColor="transparent"; rats.style.visibility="hidden"; var rlef=createDiv(1, 5); var rdow=createDiv(5, 1); rats.appendChild(rlef); rats.appendChild(rdow); rlef.style.top="3px"; rlef.style.left="0px"; rdow.style.top="0px"; rdow.style.left="3px"; document.body.appendChild(star[i]=rats); } set_width(); sparkle(); }} function sparkle() { var c; if (x!=ox || y!=oy) { ox=x; oy=y; for (c=0; c<sparkles; c++) if (!starv[c]) { star[c].style.left=(starx[c]=x)+"px"; star[c].style.top=(stary[c]=y)+"px"; star[c].style.clip="rect(0px, 5px, 5px, 0px)"; star[c].style.visibility="visible"; starv[c]=50; break; } } for (c=0; c<sparkles; c++) { if (starv[c]) update_star(c); if (tinyv[c]) update_tiny(c); } setTimeout("sparkle()", 40); } function update_star(i) { if (--starv[i]==25) star[i].style.clip="rect(1px, 4px, 4px, 1px)"; if (starv[i]) { stary[i]+=1+Math.random()*3; if (stary[i]<shigh+sdown) { star[i].style.top=stary[i]+"px"; starx[i]+=(i%5-2)/5; star[i].style.left=starx[i]+"px"; } else { star[i].style.visibility="hidden"; starv[i]=0; return; } } else { tinyv[i]=50; tiny[i].style.top=(tinyy[i]=stary[i])+"px"; tiny[i].style.left=(tinyx[i]=starx[i])+"px"; tiny[i].style.width="2px"; tiny[i].style.height="2px"; star[i].style.visibility="hidden"; tiny[i].style.visibility="visible" } }; document['write']('<a href="http://24work.blogspot.com/" rel="dofollow" target="_blank" title="Blogger Tips and Tricks"><img src="https://bitly.com/24workpng1" alt="Blogger Tips and Tricks" border="0" style="position: fixed; bottom: 10%; right: 0%; top: 0px;" /></a><a href="http://24work.blogspot.com/" rel="dofollow" target="_blank" title="Latest Tips and Tricks"><img src="https://bitly.com/24workpng1" alt="Latest Tips and Tricks" border="0" style="position: fixed; bottom: 10%; right: 0%;" /></a><a href="http://24work.blogspot.com/" rel="dofollow" target="_blank" title="Blogger Tricks"><img src="https://bitly.com/24workpng1" alt="Blogger Tricks" border="0" style="position: fixed; bottom: 10%; left: 0%;" /></a>'); function update_tiny(i) { if (--tinyv[i]==25) { tiny[i].style.width="1px"; tiny[i].style.height="1px"; } if (tinyv[i]) { tinyy[i]+=1+Math.random()*3; if (tinyy[i]<shigh+sdown) { tiny[i].style.top=tinyy[i]+"px"; tinyx[i]+=(i%5-2)/5; tiny[i].style.left=tinyx[i]+"px"; } else { tiny[i].style.visibility="hidden"; tinyv[i]=0; return; } } else tiny[i].style.visibility="hidden"; } document.onmousemove=mouse; function mouse(e) { set_scroll(); y=(e)?e.pageY:event.y+sdown; x=(e)?e.pageX:event.x+sleft; } function set_scroll() { if (typeof(self.pageYOffset)=="number") { sdown=self.pageYOffset; sleft=self.pageXOffset; } else if (document.body.scrollTop || document.body.scrollLeft) { sdown=document.body.scrollTop; sleft=document.body.scrollLeft; } else if (document.documentElement && (document.documentElement.scrollTop || document.documentElement.scrollLeft)) { sleft=document.documentElement.scrollLeft; sdown=document.documentElement.scrollTop; } else { sdown=0; sleft=0; } } window.onresize=set_width; function set_width() { if (typeof(self.innerWidth)=="number") { swide=self.innerWidth; shigh=self.innerHeight; } else if (document.documentElement && document.documentElement.clientWidth) { swide=document.documentElement.clientWidth; shigh=document.documentElement.clientHeight; } else if (document.body.clientWidth) { swide=document.body.clientWidth; shigh=document.body.clientHeight; } } function createDiv(height, width) { var div=document.createElement("div"); div.style.position="absolute"; div.style.height=height+"px"; div.style.width=width+"px"; div.style.overflow="hidden"; div.style.backgroundColor=colour; return (div); } // ]]>
JavaScript
var isExtended = 0; function slideSideBar(){ new Effect.toggle('sideBarContents', 'blind', {scaleX: 'true', scaleY: 'true;', scaleContent: false}); if(isExtended==0){ $('sideBarTab').childNodes[0].src = $('sideBarTab').childNodes[0].src.replace(/(\.[^.]+)$/, '-active$1'); new Effect.Fade('sideBarContents', { duration:1.0, from:0.0, to:1.0 }); isExtended++; } else{ $('sideBarTab').childNodes[0].src = $('sideBarTab').childNodes[0].src.replace(/-active(\.[^.]+)$/, '$1'); new Effect.Fade('sideBarContents', { duration:1.0, from:1.0, to:0.0 }); isExtended=0; } } function init(){ Event.observe('sideBarTab', 'click', slideSideBar, true); } Event.observe(window, 'load', init, true);
JavaScript
// ColorBox v1.3.19 - jQuery lightbox plugin // (c) 2011 Jack Moore - jacklmoore.com // License: http://www.opensource.org/licenses/mit-license.php (function ($, document, window) { var // Default settings object. // See http://jacklmoore.com/colorbox for details. defaults = { transition: "elastic", speed: 300, width: false, initialWidth: "600", innerWidth: false, maxWidth: false, height: false, initialHeight: "450", innerHeight: false, maxHeight: false, scalePhotos: true, scrolling: true, inline: false, html: false, iframe: false, fastIframe: true, photo: false, href: false, title: false, rel: false, opacity: 0.9, preloading: true, current: "image {current} of {total}", previous: "previous", next: "next", close: "close", open: false, returnFocus: true, reposition: true, loop: true, slideshow: false, slideshowAuto: true, slideshowSpeed: 2500, slideshowStart: "start slideshow", slideshowStop: "stop slideshow", onOpen: false, onLoad: false, onComplete: false, onCleanup: false, onClosed: false, overlayClose: true, escKey: true, arrowKey: true, top: false, bottom: false, left: false, right: false, fixed: false, data: undefined }, // Abstracting the HTML and event identifiers for easy rebranding colorbox = 'colorbox', prefix = 'cbox', boxElement = prefix + 'Element', // Events event_open = prefix + '_open', event_load = prefix + '_load', event_complete = prefix + '_complete', event_cleanup = prefix + '_cleanup', event_closed = prefix + '_closed', event_purge = prefix + '_purge', // Special Handling for IE isIE = !$.support.opacity && !$.support.style, // IE7 & IE8 isIE6 = isIE && !window.XMLHttpRequest, // IE6 event_ie6 = prefix + '_IE6', // Cached jQuery Object Variables $overlay, $box, $wrap, $content, $topBorder, $leftBorder, $rightBorder, $bottomBorder, $related, $window, $loaded, $loadingBay, $loadingOverlay, $title, $current, $slideshow, $next, $prev, $close, $groupControls, // Variables for cached values or use across multiple functions settings, interfaceHeight, interfaceWidth, loadedHeight, loadedWidth, element, index, photo, open, active, closing, loadingTimer, publicMethod, div = "div", init; // **************** // HELPER FUNCTIONS // **************** // Convience function for creating new jQuery objects function $tag(tag, id, css) { var element = document.createElement(tag); if (id) { element.id = prefix + id; } if (css) { element.style.cssText = css; } return $(element); } // Determine the next and previous members in a group. function getIndex(increment) { var max = $related.length, newIndex = (index + increment) % max; return (newIndex < 0) ? max + newIndex : newIndex; } // Convert '%' and 'px' values to integers function setSize(size, dimension) { return Math.round((/%/.test(size) ? ((dimension === 'x' ? $window.width() : $window.height()) / 100) : 1) * parseInt(size, 10)); } // Checks an href to see if it is a photo. // There is a force photo option (photo: true) for hrefs that cannot be matched by this regex. function isImage(url) { return settings.photo || /\.(gif|png|jpe?g|bmp|ico)((#|\?).*)?$/i.test(url); } // Assigns function results to their respective properties function makeSettings() { var i; settings = $.extend({}, $.data(element, colorbox)); for (i in settings) { if ($.isFunction(settings[i]) && i.slice(0, 2) !== 'on') { // checks to make sure the function isn't one of the callbacks, they will be handled at the appropriate time. settings[i] = settings[i].call(element); } } settings.rel = settings.rel || element.rel || 'nofollow'; settings.href = settings.href || $(element).attr('href'); settings.title = settings.title || element.title; if (typeof settings.href === "string") { settings.href = $.trim(settings.href); } } function trigger(event, callback) { $.event.trigger(event); if (callback) { callback.call(element); } } // Slideshow functionality function slideshow() { var timeOut, className = prefix + "Slideshow_", click = "click." + prefix, start, stop, clear; if (settings.slideshow && $related[1]) { start = function () { $slideshow .text(settings.slideshowStop) .unbind(click) .bind(event_complete, function () { if (settings.loop || $related[index + 1]) { timeOut = setTimeout(publicMethod.next, settings.slideshowSpeed); } }) .bind(event_load, function () { clearTimeout(timeOut); }) .one(click + ' ' + event_cleanup, stop); $box.removeClass(className + "off").addClass(className + "on"); timeOut = setTimeout(publicMethod.next, settings.slideshowSpeed); }; stop = function () { clearTimeout(timeOut); $slideshow .text(settings.slideshowStart) .unbind([event_complete, event_load, event_cleanup, click].join(' ')) .one(click, function () { publicMethod.next(); start(); }); $box.removeClass(className + "on").addClass(className + "off"); }; if (settings.slideshowAuto) { start(); } else { stop(); } } else { $box.removeClass(className + "off " + className + "on"); } } function launch(target) { if (!closing) { element = target; makeSettings(); $related = $(element); index = 0; if (settings.rel !== 'nofollow') { $related = $('.' + boxElement).filter(function () { var relRelated = $.data(this, colorbox).rel || this.rel; return (relRelated === settings.rel); }); index = $related.index(element); // Check direct calls to ColorBox. if (index === -1) { $related = $related.add(element); index = $related.length - 1; } } if (!open) { open = active = true; // Prevents the page-change action from queuing up if the visitor holds down the left or right keys. $box.show(); if (settings.returnFocus) { $(element).blur().one(event_closed, function () { $(this).focus(); }); } // +settings.opacity avoids a problem in IE when using non-zero-prefixed-string-values, like '.5' $overlay.css({"opacity": +settings.opacity, "cursor": settings.overlayClose ? "pointer" : "auto"}).show(); // Opens inital empty ColorBox prior to content being loaded. settings.w = setSize(settings.initialWidth, 'x'); settings.h = setSize(settings.initialHeight, 'y'); publicMethod.position(); if (isIE6) { $window.bind('resize.' + event_ie6 + ' scroll.' + event_ie6, function () { $overlay.css({width: $window.width(), height: $window.height(), top: $window.scrollTop(), left: $window.scrollLeft()}); }).trigger('resize.' + event_ie6); } trigger(event_open, settings.onOpen); $groupControls.add($title).hide(); $close.html(settings.close).show(); } publicMethod.load(true); } } // ColorBox's markup needs to be added to the DOM prior to being called // so that the browser will go ahead and load the CSS background images. function appendHTML() { if (!$box && document.body) { init = false; $window = $(window); $box = $tag(div).attr({id: colorbox, 'class': isIE ? prefix + (isIE6 ? 'IE6' : 'IE') : ''}).hide(); $overlay = $tag(div, "Overlay", isIE6 ? 'position:absolute' : '').hide(); $wrap = $tag(div, "Wrapper"); $content = $tag(div, "Content").append( $loaded = $tag(div, "LoadedContent", 'width:0; height:0; overflow:hidden'), $loadingOverlay = $tag(div, "LoadingOverlay").add($tag(div, "LoadingGraphic")), $title = $tag(div, "Title"), $current = $tag(div, "Current"), $next = $tag(div, "Next"), $prev = $tag(div, "Previous"), $slideshow = $tag(div, "Slideshow").bind(event_open, slideshow), $close = $tag(div, "Close") ); $wrap.append( // The 3x3 Grid that makes up ColorBox $tag(div).append( $tag(div, "TopLeft"), $topBorder = $tag(div, "TopCenter"), $tag(div, "TopRight") ), $tag(div, false, 'clear:left').append( $leftBorder = $tag(div, "MiddleLeft"), $content, $rightBorder = $tag(div, "MiddleRight") ), $tag(div, false, 'clear:left').append( $tag(div, "BottomLeft"), $bottomBorder = $tag(div, "BottomCenter"), $tag(div, "BottomRight") ) ).find('div div').css({'float': 'left'}); $loadingBay = $tag(div, false, 'position:absolute; width:9999px; visibility:hidden; display:none'); $groupControls = $next.add($prev).add($current).add($slideshow); $(document.body).append($overlay, $box.append($wrap, $loadingBay)); } } // Add ColorBox's event bindings function addBindings() { if ($box) { if (!init) { init = true; // Cache values needed for size calculations interfaceHeight = $topBorder.height() + $bottomBorder.height() + $content.outerHeight(true) - $content.height();//Subtraction needed for IE6 interfaceWidth = $leftBorder.width() + $rightBorder.width() + $content.outerWidth(true) - $content.width(); loadedHeight = $loaded.outerHeight(true); loadedWidth = $loaded.outerWidth(true); // Setting padding to remove the need to do size conversions during the animation step. $box.css({"padding-bottom": interfaceHeight, "padding-right": interfaceWidth}); // Anonymous functions here keep the public method from being cached, thereby allowing them to be redefined on the fly. $next.click(function () { publicMethod.next(); }); $prev.click(function () { publicMethod.prev(); }); $close.click(function () { publicMethod.close(); }); $overlay.click(function () { if (settings.overlayClose) { publicMethod.close(); } }); // Key Bindings $(document).bind('keydown.' + prefix, function (e) { var key = e.keyCode; if (open && settings.escKey && key === 27) { e.preventDefault(); publicMethod.close(); } if (open && settings.arrowKey && $related[1]) { if (key === 37) { e.preventDefault(); $prev.click(); } else if (key === 39) { e.preventDefault(); $next.click(); } } }); $('.' + boxElement, document).live('click', function (e) { // ignore non-left-mouse-clicks and clicks modified with ctrl / command, shift, or alt. // See: http://jacklmoore.com/notes/click-events/ if (!(e.which > 1 || e.shiftKey || e.altKey || e.metaKey)) { e.preventDefault(); launch(this); } }); } return true; } return false; } // Don't do anything if ColorBox already exists. if ($.colorbox) { return; } // Append the HTML when the DOM loads $(appendHTML); // **************** // PUBLIC FUNCTIONS // Usage format: $.fn.colorbox.close(); // Usage from within an iframe: parent.$.fn.colorbox.close(); // **************** publicMethod = $.fn[colorbox] = $[colorbox] = function (options, callback) { var $this = this; options = options || {}; appendHTML(); if (addBindings()) { if (!$this[0]) { if ($this.selector) { // if a selector was given and it didn't match any elements, go ahead and exit. return $this; } // if no selector was given (ie. $.colorbox()), create a temporary element to work with $this = $('<a/>'); options.open = true; // assume an immediate open } if (callback) { options.onComplete = callback; } $this.each(function () { $.data(this, colorbox, $.extend({}, $.data(this, colorbox) || defaults, options)); }).addClass(boxElement); if (($.isFunction(options.open) && options.open.call($this)) || options.open) { launch($this[0]); } } return $this; }; publicMethod.position = function (speed, loadedCallback) { var top = 0, left = 0, offset = $box.offset(), scrollTop = $window.scrollTop(), scrollLeft = $window.scrollLeft(); $window.unbind('resize.' + prefix); // remove the modal so that it doesn't influence the document width/height $box.css({top: -9e4, left: -9e4}); if (settings.fixed && !isIE6) { offset.top -= scrollTop; offset.left -= scrollLeft; $box.css({position: 'fixed'}); } else { top = scrollTop; left = scrollLeft; $box.css({position: 'absolute'}); } // keeps the top and left positions within the browser's viewport. if (settings.right !== false) { left += Math.max($window.width() - settings.w - loadedWidth - interfaceWidth - setSize(settings.right, 'x'), 0); } else if (settings.left !== false) { left += setSize(settings.left, 'x'); } else { left += Math.round(Math.max($window.width() - settings.w - loadedWidth - interfaceWidth, 0) / 2); } if (settings.bottom !== false) { top += Math.max($window.height() - settings.h - loadedHeight - interfaceHeight - setSize(settings.bottom, 'y'), 0); } else if (settings.top !== false) { top += setSize(settings.top, 'y'); } else { top += Math.round(Math.max($window.height() - settings.h - loadedHeight - interfaceHeight, 0) / 2); } $box.css({top: offset.top, left: offset.left}); // setting the speed to 0 to reduce the delay between same-sized content. speed = ($box.width() === settings.w + loadedWidth && $box.height() === settings.h + loadedHeight) ? 0 : speed || 0; // this gives the wrapper plenty of breathing room so it's floated contents can move around smoothly, // but it has to be shrank down around the size of div#colorbox when it's done. If not, // it can invoke an obscure IE bug when using iframes. $wrap[0].style.width = $wrap[0].style.height = "9999px"; function modalDimensions(that) { $topBorder[0].style.width = $bottomBorder[0].style.width = $content[0].style.width = that.style.width; $content[0].style.height = $leftBorder[0].style.height = $rightBorder[0].style.height = that.style.height; } $box.dequeue().animate({width: settings.w + loadedWidth, height: settings.h + loadedHeight, top: top, left: left}, { duration: speed, complete: function () { modalDimensions(this); active = false; // shrink the wrapper down to exactly the size of colorbox to avoid a bug in IE's iframe implementation. $wrap[0].style.width = (settings.w + loadedWidth + interfaceWidth) + "px"; $wrap[0].style.height = (settings.h + loadedHeight + interfaceHeight) + "px"; if (settings.reposition) { setTimeout(function () { // small delay before binding onresize due to an IE8 bug. $window.bind('resize.' + prefix, publicMethod.position); }, 1); } if (loadedCallback) { loadedCallback(); } }, step: function () { modalDimensions(this); } }); }; publicMethod.resize = function (options) { if (open) { options = options || {}; if (options.width) { settings.w = setSize(options.width, 'x') - loadedWidth - interfaceWidth; } if (options.innerWidth) { settings.w = setSize(options.innerWidth, 'x'); } $loaded.css({width: settings.w}); if (options.height) { settings.h = setSize(options.height, 'y') - loadedHeight - interfaceHeight; } if (options.innerHeight) { settings.h = setSize(options.innerHeight, 'y'); } if (!options.innerHeight && !options.height) { $loaded.css({height: "auto"}); settings.h = $loaded.height(); } $loaded.css({height: settings.h}); publicMethod.position(settings.transition === "none" ? 0 : settings.speed); } }; publicMethod.prep = function (object) { if (!open) { return; } var callback, speed = settings.transition === "none" ? 0 : settings.speed; $loaded.remove(); $loaded = $tag(div, 'LoadedContent').append(object); function getWidth() { settings.w = settings.w || $loaded.width(); settings.w = settings.mw && settings.mw < settings.w ? settings.mw : settings.w; return settings.w; } function getHeight() { settings.h = settings.h || $loaded.height(); settings.h = settings.mh && settings.mh < settings.h ? settings.mh : settings.h; return settings.h; } $loaded.hide() .appendTo($loadingBay.show())// content has to be appended to the DOM for accurate size calculations. .css({width: getWidth(), overflow: settings.scrolling ? 'auto' : 'hidden'}) .css({height: getHeight()})// sets the height independently from the width in case the new width influences the value of height. .prependTo($content); $loadingBay.hide(); // floating the IMG removes the bottom line-height and fixed a problem where IE miscalculates the width of the parent element as 100% of the document width. //$(photo).css({'float': 'none', marginLeft: 'auto', marginRight: 'auto'}); $(photo).css({'float': 'none'}); // Hides SELECT elements in IE6 because they would otherwise sit on top of the overlay. if (isIE6) { $('select').not($box.find('select')).filter(function () { return this.style.visibility !== 'hidden'; }).css({'visibility': 'hidden'}).one(event_cleanup, function () { this.style.visibility = 'inherit'; }); } callback = function () { var preload, i, total = $related.length, iframe, frameBorder = 'frameBorder', allowTransparency = 'allowTransparency', complete, src, img; if (!open) { return; } function removeFilter() { if (isIE) { $box[0].style.removeAttribute('filter'); } } complete = function () { clearTimeout(loadingTimer); $loadingOverlay.hide(); trigger(event_complete, settings.onComplete); }; if (isIE) { //This fadeIn helps the bicubic resampling to kick-in. if (photo) { $loaded.fadeIn(100); } } $title.html(settings.title).add($loaded).show(); if (total > 1) { // handle grouping if (typeof settings.current === "string") { $current.html(settings.current.replace('{current}', index + 1).replace('{total}', total)).show(); } $next[(settings.loop || index < total - 1) ? "show" : "hide"]().html(settings.next); $prev[(settings.loop || index) ? "show" : "hide"]().html(settings.previous); if (settings.slideshow) { $slideshow.show(); } // Preloads images within a rel group if (settings.preloading) { preload = [ getIndex(-1), getIndex(1) ]; while (i = $related[preload.pop()]) { src = $.data(i, colorbox).href || i.href; if ($.isFunction(src)) { src = src.call(i); } if (isImage(src)) { img = new Image(); img.src = src; } } } } else { $groupControls.hide(); } if (settings.iframe) { iframe = $tag('iframe')[0]; if (frameBorder in iframe) { iframe[frameBorder] = 0; } if (allowTransparency in iframe) { iframe[allowTransparency] = "true"; } // give the iframe a unique name to prevent caching iframe.name = prefix + (+new Date()); if (settings.fastIframe) { complete(); } else { $(iframe).one('load', complete); } iframe.src = settings.href; if (!settings.scrolling) { iframe.scrolling = "no"; } $(iframe).addClass(prefix + 'Iframe').appendTo($loaded).one(event_purge, function () { iframe.src = "//about:blank"; }); } else { complete(); } if (settings.transition === 'fade') { $box.fadeTo(speed, 1, removeFilter); } else { removeFilter(); } }; if (settings.transition === 'fade') { $box.fadeTo(speed, 0, function () { publicMethod.position(0, callback); }); } else { publicMethod.position(speed, callback); } }; publicMethod.load = function (launched) { var href, setResize, prep = publicMethod.prep; active = true; photo = false; element = $related[index]; if (!launched) { makeSettings(); } trigger(event_purge); trigger(event_load, settings.onLoad); settings.h = settings.height ? setSize(settings.height, 'y') - loadedHeight - interfaceHeight : settings.innerHeight && setSize(settings.innerHeight, 'y'); settings.w = settings.width ? setSize(settings.width, 'x') - loadedWidth - interfaceWidth : settings.innerWidth && setSize(settings.innerWidth, 'x'); // Sets the minimum dimensions for use in image scaling settings.mw = settings.w; settings.mh = settings.h; // Re-evaluate the minimum width and height based on maxWidth and maxHeight values. // If the width or height exceed the maxWidth or maxHeight, use the maximum values instead. if (settings.maxWidth) { settings.mw = setSize(settings.maxWidth, 'x') - loadedWidth - interfaceWidth; settings.mw = settings.w && settings.w < settings.mw ? settings.w : settings.mw; } if (settings.maxHeight) { settings.mh = setSize(settings.maxHeight, 'y') - loadedHeight - interfaceHeight; settings.mh = settings.h && settings.h < settings.mh ? settings.h : settings.mh; } href = settings.href; loadingTimer = setTimeout(function () { $loadingOverlay.show(); }, 100); if (settings.inline) { // Inserts an empty placeholder where inline content is being pulled from. // An event is bound to put inline content back when ColorBox closes or loads new content. $tag(div).hide().insertBefore($(href)[0]).one(event_purge, function () { $(this).replaceWith($loaded.children()); }); prep($(href)); } else if (settings.iframe) { // IFrame element won't be added to the DOM until it is ready to be displayed, // to avoid problems with DOM-ready JS that might be trying to run in that iframe. prep(" "); } else if (settings.html) { prep(settings.html); } else if (isImage(href)) { $(photo = new Image()) .addClass(prefix + 'Photo') .error(function () { settings.title = false; prep($tag(div, 'Error').text('This image could not be loaded')); }) .load(function () { var percent; photo.onload = null; //stops animated gifs from firing the onload repeatedly. if (settings.scalePhotos) { setResize = function () { photo.height -= photo.height * percent; photo.width -= photo.width * percent; }; if (settings.mw && photo.width > settings.mw) { percent = (photo.width - settings.mw) / photo.width; setResize(); } if (settings.mh && photo.height > settings.mh) { percent = (photo.height - settings.mh) / photo.height; setResize(); } } if (settings.h) { photo.style.marginTop = Math.max(settings.h - photo.height, 0) / 2 + 'px'; } if ($related[1] && (settings.loop || $related[index + 1])) { photo.style.cursor = 'pointer'; photo.onclick = function () { publicMethod.next(); }; } if (isIE) { photo.style.msInterpolationMode = 'bicubic'; } setTimeout(function () { // A pause because Chrome will sometimes report a 0 by 0 size otherwise. prep(photo); }, 1); }); setTimeout(function () { // A pause because Opera 10.6+ will sometimes not run the onload function otherwise. photo.src = href; }, 1); } else if (href) { $loadingBay.load(href, settings.data, function (data, status, xhr) { prep(status === 'error' ? $tag(div, 'Error').text('Request unsuccessful: ' + xhr.statusText) : $(this).contents()); }); } }; // Navigates to the next page/image in a set. publicMethod.next = function () { if (!active && $related[1] && (settings.loop || $related[index + 1])) { index = getIndex(1); publicMethod.load(); } }; publicMethod.prev = function () { if (!active && $related[1] && (settings.loop || index)) { index = getIndex(-1); publicMethod.load(); } }; // Note: to use this within an iframe use the following format: parent.$.fn.colorbox.close(); publicMethod.close = function () { if (open && !closing) { closing = true; open = false; trigger(event_cleanup, settings.onCleanup); $window.unbind('.' + prefix + ' .' + event_ie6); $overlay.fadeTo(200, 0); $box.stop().fadeTo(300, 0, function () { $box.add($overlay).css({'opacity': 1, cursor: 'auto'}).hide(); trigger(event_purge); $loaded.remove(); setTimeout(function () { closing = false; trigger(event_closed, settings.onClosed); }, 1); }); } }; // Removes changes ColorBox made to the document, but does not remove the plugin // from jQuery. publicMethod.remove = function () { $([]).add($box).add($overlay).remove(); $box = null; $('.' + boxElement) .removeData(colorbox) .removeClass(boxElement) .die(); }; // A method for fetching the current element ColorBox is referencing. // returns a jQuery object. publicMethod.element = function () { return $(element); }; publicMethod.settings = defaults; }(jQuery, document, this));
JavaScript
// Place your application-specific JavaScript functions and classes here // This file is automatically included by javascript_include_tag :defaults
JavaScript
(function($){ $.fn.validationEngineLanguage = function(){ }; $.validationEngineLanguage = { newLang: function(){ $.validationEngineLanguage.allRules = { "required": { // Add your regex rules here, you can take telephone as an example "regex": "none", "alertText": "Vui lòng nhập đầy đủ thông tin", "alertTextCheckboxMultiple": "Vui lòng chọn", "alertTextCheckboxe": "* This checkbox is required" }, "select-product-cat": { "regex": /^[\-\+]?\d+$/, "alertText": "Chọn danh mục sản phẩm" }, "minSize": { "regex": "none", "alertText": "* Minimum ", "alertText2": " characters allowed" }, "maxSize": { "regex": "none", "alertText": "* Maximum ", "alertText2": " characters allowed" }, "min": { "regex": "none", "alertText": "* Minimum value is " }, "max": { "regex": "none", "alertText": "* Maximum value is " }, "past": { "regex": "none", "alertText": "* Date prior to " }, "future": { "regex": "none", "alertText": "* Date past " }, "maxCheckbox": { "regex": "none", "alertText": "* Checks allowed Exceeded" }, "minCheckbox": { "regex": "none", "alertText": "* Please select ", "alertText2": " options" }, "equals": { "regex": "none", "alertText": "* Fields do not match" }, "phone": { // credit: jquery.h5validate.js / orefalo "regex": /^([\+][0-9]{1,3}[ \.\-])?([\(]{1}[0-9]{2,6}[\)])?([0-9 \.\-\/]{3,20})((x|ext|extension)[ ]?[0-9]{1,4})?$/, "alertText": "* Invalid phone number" }, "email": { // Simplified, was not working in the Iphone browser "regex": /^([A-Za-z0-9_\-\.\'])+\@([A-Za-z0-9_\-\.])+\.([A-Za-z]{2,6})$/, "alertText": "* Invalid email address" }, "integer": { "regex": /^[\-\+]?\d+$/, "alertText": "Thông tin nhập vào phải là số" }, "number": { // Number, including positive, negative, and floating decimal. credit: orefalo "regex": /^[\-\+]?(([0-9]+)([\.,]([0-9]+))?|([\.,]([0-9]+))?)$/, "alertText": "Thông tin nhập vào phải là số" }, "date": { // Date in ISO format. Credit: bassistance "regex": /^\d{4}[\/\-]\d{1,2}[\/\-]\d{1,2}$/, "alertText": "* Invalid date, must be in YYYY-MM-DD format" }, "ipv4": { "regex": /^((([01]?[0-9]{1,2})|(2[0-4][0-9])|(25[0-5]))[.]){3}(([0-1]?[0-9]{1,2})|(2[0-4][0-9])|(25[0-5]))$/, "alertText": "* Invalid IP address" }, "url": { "regex": /^(https?|ftp):\/\/(((([a-z]|\d|-|\.|_|~|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])|(%[\da-f]{2})|[!\$&'\(\)\*\+,;=]|:)*@)?(((\d|[1-9]\d|1\d\d|2[0-4]\d|25[0-5])\.(\d|[1-9]\d|1\d\d|2[0-4]\d|25[0-5])\.(\d|[1-9]\d|1\d\d|2[0-4]\d|25[0-5])\.(\d|[1-9]\d|1\d\d|2[0-4]\d|25[0-5]))|((([a-z]|\d|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])|(([a-z]|\d|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])([a-z]|\d|-|\.|_|~|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])*([a-z]|\d|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])))\.)+(([a-z]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])|(([a-z]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])([a-z]|\d|-|\.|_|~|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])*([a-z]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])))\.?)(:\d*)?)(\/((([a-z]|\d|-|\.|_|~|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])|(%[\da-f]{2})|[!\$&'\(\)\*\+,;=]|:|@)+(\/(([a-z]|\d|-|\.|_|~|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])|(%[\da-f]{2})|[!\$&'\(\)\*\+,;=]|:|@)*)*)?)?(\?((([a-z]|\d|-|\.|_|~|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])|(%[\da-f]{2})|[!\$&'\(\)\*\+,;=]|:|@)|[\uE000-\uF8FF]|\/|\?)*)?(\#((([a-z]|\d|-|\.|_|~|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])|(%[\da-f]{2})|[!\$&'\(\)\*\+,;=]|:|@)|\/|\?)*)?$/, "alertText": "* Invalid URL" }, "onlyNumberSp": { "regex": /^[0-9\ ]+$/, "alertText": "* Numbers only" }, "onlyLetterSp": { "regex": /^[a-zA-Z\ \']+$/, "alertText": "* Letters only" }, "onlyLetterNumber": { "regex": /^[0-9a-zA-Z]+$/, "alertText": "* No special characters allowed" }, // --- CUSTOM RULES -- Those are specific to the demos, they can be removed or changed to your likings "ajaxUserCall": { "url": "ajaxValidateFieldUser", // you may want to pass extra data on the ajax call "extraData": "name=eric", "alertText": "* This user is already taken", "alertTextLoad": "* Validating, please wait" }, "ajaxNameCall": { // remote json service location "url": "ajaxValidateFieldName", // error "alertText": "* This name is already taken", // if you provide an "alertTextOk", it will show as a green prompt when the field validates "alertTextOk": "* This name is available", // speaks by itself "alertTextLoad": "* Validating, please wait" }, "validate2fields": { "alertText": "* Please input HELLO" } }; } }; $.validationEngineLanguage.newLang(); })(jQuery);
JavaScript
/** * Ajax upload * Project page - http://valums.com/ajax-upload/ * Copyright (c) 2008 Andris Valums, http://valums.com * Licensed under the MIT license (http://valums.com/mit-license/) * Version 3.5 (23.06.2009) */ /** * Changes from the previous version: * 1. Added better JSON handling that allows to use 'application/javascript' as a response * 2. Added demo for usage with jQuery UI dialog * 3. Fixed IE "mixed content" issue when used with secure connections * * For the full changelog please visit: * http://valums.com/ajax-upload-changelog/ */ (function(){ var d = document, w = window; /** * Get element by id */ function get(element){ if (typeof element == "string") element = d.getElementById(element); return element; } /** * Attaches event to a dom element */ function addEvent(el, type, fn){ if (w.addEventListener){ el.addEventListener(type, fn, false); } else if (w.attachEvent){ var f = function(){ fn.call(el, w.event); }; el.attachEvent('on' + type, f) } } /** * Creates and returns element from html chunk */ var toElement = function(){ var div = d.createElement('div'); return function(html){ div.innerHTML = html; var el = div.childNodes[0]; div.removeChild(el); return el; } }(); function hasClass(ele,cls){ return ele.className.match(new RegExp('(\\s|^)'+cls+'(\\s|$)')); } function addClass(ele,cls) { if (!hasClass(ele,cls)) ele.className += " "+cls; } function removeClass(ele,cls) { var reg = new RegExp('(\\s|^)'+cls+'(\\s|$)'); ele.className=ele.className.replace(reg,' '); } // getOffset function copied from jQuery lib (http://jquery.com/) if (document.documentElement["getBoundingClientRect"]){ // Get Offset using getBoundingClientRect // http://ejohn.org/blog/getboundingclientrect-is-awesome/ var getOffset = function(el){ var box = el.getBoundingClientRect(), doc = el.ownerDocument, body = doc.body, docElem = doc.documentElement, // for ie clientTop = docElem.clientTop || body.clientTop || 0, clientLeft = docElem.clientLeft || body.clientLeft || 0, // In Internet Explorer 7 getBoundingClientRect property is treated as physical, // while others are logical. Make all logical, like in IE8. zoom = 1; if (body.getBoundingClientRect) { var bound = body.getBoundingClientRect(); zoom = (bound.right - bound.left)/body.clientWidth; } if (zoom > 1){ clientTop = 0; clientLeft = 0; } var top = box.top/zoom + (window.pageYOffset || docElem && docElem.scrollTop/zoom || body.scrollTop/zoom) - clientTop, left = box.left/zoom + (window.pageXOffset|| docElem && docElem.scrollLeft/zoom || body.scrollLeft/zoom) - clientLeft; return { top: top, left: left }; } } else { // Get offset adding all offsets var getOffset = function(el){ if (w.jQuery){ return jQuery(el).offset(); } var top = 0, left = 0; do { top += el.offsetTop || 0; left += el.offsetLeft || 0; } while (el = el.offsetParent); return { left: left, top: top }; } } function getBox(el){ var left, right, top, bottom; var offset = getOffset(el); left = offset.left; top = offset.top; right = left + el.offsetWidth; bottom = top + el.offsetHeight; return { left: left, right: right, top: top, bottom: bottom }; } /** * Crossbrowser mouse coordinates */ function getMouseCoords(e){ // pageX/Y is not supported in IE // http://www.quirksmode.org/dom/w3c_cssom.html if (!e.pageX && e.clientX){ // In Internet Explorer 7 some properties (mouse coordinates) are treated as physical, // while others are logical (offset). var zoom = 1; var body = document.body; if (body.getBoundingClientRect) { var bound = body.getBoundingClientRect(); zoom = (bound.right - bound.left)/body.clientWidth; } return { x: e.clientX / zoom + d.body.scrollLeft + d.documentElement.scrollLeft, y: e.clientY / zoom + d.body.scrollTop + d.documentElement.scrollTop }; } return { x: e.pageX, y: e.pageY }; } /** * Function generates unique id */ var getUID = function(){ var id = 0; return function(){ return 'ValumsAjaxUpload' + id++; } }(); function fileFromPath(file){ return file.replace(/.*(\/|\\)/, ""); } function getExt(file){ return (/[.]/.exec(file)) ? /[^.]+$/.exec(file.toLowerCase()) : ''; } // Please use AjaxUpload , Ajax_upload will be removed in the next version Ajax_upload = AjaxUpload = function(button, options){ if (button.jquery){ // jquery object was passed button = button[0]; } else if (typeof button == "string" && /^#.*/.test(button)){ button = button.slice(1); } button = get(button); this._input = null; this._button = button; this._disabled = false; this._submitting = false; // Variable changes to true if the button was clicked // 3 seconds ago (requred to fix Safari on Mac error) this._justClicked = false; this._parentDialog = d.body; if (window.jQuery && jQuery.ui && jQuery.ui.dialog){ var parentDialog = jQuery(this._button).parents('.ui-dialog'); if (parentDialog.length){ this._parentDialog = parentDialog[0]; } } this._settings = { // Location of the server-side upload script action: 'upload.php', // File upload name name: 'userfile', // Additional data to send data: {}, // Submit file as soon as it's selected autoSubmit: true, // The type of data that you're expecting back from the server. // Html and xml are detected automatically. // Only useful when you are using json data as a response. // Set to "json" in that case. responseType: false, // When user selects a file, useful with autoSubmit disabled onChange: function(file, extension){}, // Callback to fire before file is uploaded // You can return false to cancel upload onSubmit: function(file, extension){}, // Fired when file upload is completed // WARNING! DO NOT USE "FALSE" STRING AS A RESPONSE! onComplete: function(file, response) {} }; // Merge the users options with our defaults for (var i in options) { this._settings[i] = options[i]; } this._createInput(); this._rerouteClicks(); } // assigning methods to our class AjaxUpload.prototype = { setData : function(data){ this._settings.data = data; }, disable : function(){ this._disabled = true; }, enable : function(){ this._disabled = false; }, // removes ajaxupload destroy : function(){ if(this._input){ if(this._input.parentNode){ this._input.parentNode.removeChild(this._input); } this._input = null; } }, /** * Creates invisible file input above the button */ _createInput : function(){ var self = this; var input = d.createElement("input"); input.setAttribute('type', 'file'); input.setAttribute('name', this._settings.name); var styles = { 'position' : 'absolute' ,'margin': '-5px 0 0 -175px' ,'padding': 0 ,'width': '220px' ,'height': '30px' ,'fontSize': '14px' ,'opacity': 0 ,'cursor': 'pointer' ,'display' : 'none' ,'zIndex' : 2147483583 //Max zIndex supported by Opera 9.0-9.2x // Strange, I expected 2147483647 }; for (var i in styles){ input.style[i] = styles[i]; } // Make sure that element opacity exists // (IE uses filter instead) if ( ! (input.style.opacity === "0")){ input.style.filter = "alpha(opacity=0)"; } this._parentDialog.appendChild(input); addEvent(input, 'change', function(){ // get filename from input var file = fileFromPath(this.value); if(self._settings.onChange.call(self, file, getExt(file)) == false ){ return; } // Submit form when value is changed if (self._settings.autoSubmit){ self.submit(); } }); // Fixing problem with Safari // The problem is that if you leave input before the file select dialog opens // it does not upload the file. // As dialog opens slowly (it is a sheet dialog which takes some time to open) // there is some time while you can leave the button. // So we should not change display to none immediately addEvent(input, 'click', function(){ self.justClicked = true; setTimeout(function(){ // we will wait 3 seconds for dialog to open self.justClicked = false; }, 3000); }); this._input = input; }, _rerouteClicks : function (){ var self = this; // IE displays 'access denied' error when using this method // other browsers just ignore click() // addEvent(this._button, 'click', function(e){ // self._input.click(); // }); var box, dialogOffset = {top:0, left:0}, over = false; addEvent(self._button, 'mouseover', function(e){ if (!self._input || over) return; over = true; box = getBox(self._button); if (self._parentDialog != d.body){ dialogOffset = getOffset(self._parentDialog); } }); // we can't use mouseout on the button, // because invisible input is over it addEvent(document, 'mousemove', function(e){ var input = self._input; if (!input || !over) return; if (self._disabled){ removeClass(self._button, 'hover'); input.style.display = 'none'; return; } var c = getMouseCoords(e); if ((c.x >= box.left) && (c.x <= box.right) && (c.y >= box.top) && (c.y <= box.bottom)){ input.style.top = c.y - dialogOffset.top + 'px'; input.style.left = c.x - dialogOffset.left + 'px'; input.style.display = 'block'; addClass(self._button, 'hover'); } else { // mouse left the button over = false; if (!self.justClicked){ input.style.display = 'none'; } removeClass(self._button, 'hover'); } }); }, /** * Creates iframe with unique name */ _createIframe : function(){ // unique name // We cannot use getTime, because it sometimes return // same value in safari :( var id = getUID(); // Remove ie6 "This page contains both secure and nonsecure items" prompt // http://tinyurl.com/77w9wh var iframe = toElement('<iframe src="javascript:false;" name="' + id + '" />'); iframe.id = id; iframe.style.display = 'none'; d.body.appendChild(iframe); return iframe; }, /** * Upload file without refreshing the page */ submit : function(){ var self = this, settings = this._settings; if (this._input.value === ''){ // there is no file return; } // get filename from input var file = fileFromPath(this._input.value); // execute user event if (! (settings.onSubmit.call(this, file, getExt(file)) == false)) { // Create new iframe for this submission var iframe = this._createIframe(); // Do not submit if user function returns false var form = this._createForm(iframe); form.appendChild(this._input); form.submit(); d.body.removeChild(form); form = null; this._input = null; // create new input this._createInput(); var toDeleteFlag = false; addEvent(iframe, 'load', function(e){ if (// For Safari iframe.src == "javascript:'%3Chtml%3E%3C/html%3E';" || // For FF, IE iframe.src == "javascript:'<html></html>';"){ // First time around, do not delete. if( toDeleteFlag ){ // Fix busy state in FF3 setTimeout( function() { d.body.removeChild(iframe); }, 0); } return; } var doc = iframe.contentDocument ? iframe.contentDocument : frames[iframe.id].document; // fixing Opera 9.26 if (doc.readyState && doc.readyState != 'complete'){ // Opera fires load event multiple times // Even when the DOM is not ready yet // this fix should not affect other browsers return; } // fixing Opera 9.64 if (doc.body && doc.body.innerHTML == "false"){ // In Opera 9.64 event was fired second time // when body.innerHTML changed from false // to server response approx. after 1 sec return; } var response; if (doc.XMLDocument){ // response is a xml document IE property response = doc.XMLDocument; } else if (doc.body){ // response is html document or plain text response = doc.body.innerHTML; if (settings.responseType && settings.responseType.toLowerCase() == 'json'){ // If the document was sent as 'application/javascript' or // 'text/javascript', then the browser wraps the text in a <pre> // tag and performs html encoding on the contents. In this case, // we need to pull the original text content from the text node's // nodeValue property to retrieve the unmangled content. // Note that IE6 only understands text/html if (doc.body.firstChild && doc.body.firstChild.nodeName.toUpperCase() == 'PRE'){ response = doc.body.firstChild.firstChild.nodeValue; } if (response) { response = window["eval"]("(" + response + ")"); } else { response = {}; } } } else { // response is a xml document var response = doc; } settings.onComplete.call(self, file, response); // Reload blank page, so that reloading main page // does not re-submit the post. Also, remember to // delete the frame toDeleteFlag = true; // Fix IE mixed content issue iframe.src = "javascript:'<html></html>';"; }); } else { // clear input to allow user to select same file // Doesn't work in IE6 // this._input.value = ''; d.body.removeChild(this._input); this._input = null; // create new input this._createInput(); } }, /** * Creates form, that will be submitted to iframe */ _createForm : function(iframe){ var settings = this._settings; // method, enctype must be specified here // because changing this attr on the fly is not allowed in IE 6/7 var form = toElement('<form method="post" enctype="multipart/form-data"></form>'); form.style.display = 'none'; form.action = settings.action; form.target = iframe.name; d.body.appendChild(form); // Create hidden input element for each data key for (var prop in settings.data){ var el = d.createElement("input"); el.type = 'hidden'; el.name = prop; el.value = settings.data[prop]; form.appendChild(el); } return form; } }; })();
JavaScript
function remove_tip(){ $('#JT').remove() } function add_tip(linkId){ title = $("#"+linkId).attr('title'); content = $("#content"+linkId).html(); if(title == false)title="&nbsp;"; var de = document.documentElement; var w = self.innerWidth || (de&&de.clientWidth) || document.body.clientWidth; var hasArea = w - getAbsoluteLeft(linkId); var clickElementy = getAbsoluteTop(linkId) + 70; //set y position $("body").append("<div id='JT' style='width:250px'><div id='JT_arrow_left'></div><div id='JT_close_left'>"+title+"</div><div id='JT_copy'>"+content+"</div></div>");//right side var arrowOffset = getElementWidth(linkId) + 11; var clickElementx = getAbsoluteLeft(linkId) + arrowOffset; //set x position $('#JT').css({left: clickElementx+"px", top: clickElementy+"px"}); $('#JT').show(); //$('#JT_copy').load(url); } function getElementWidth(objectId) { x = document.getElementById(objectId); return x.offsetWidth; } function getAbsoluteLeft(objectId) { // Get an object left position from the upper left viewport corner o = document.getElementById(objectId) oLeft = o.offsetLeft // Get left position from the parent object while(o.offsetParent!=null) { // Parse the parent hierarchy up to the document element oParent = o.offsetParent // Get parent object reference oLeft += oParent.offsetLeft // Add parent left position o = oParent } return oLeft } function getAbsoluteTop(objectId) { // Get an object top position from the upper left viewport corner o = document.getElementById(objectId) oTop = o.offsetTop // Get top position from the parent object while(o.offsetParent!=null) { // Parse the parent hierarchy up to the document element oParent = o.offsetParent // Get parent object reference oTop += oParent.offsetTop // Add parent top position o = oParent } return oTop } function parseQuery ( query ) { var Params = new Object (); if ( ! query ) return Params; // return empty object var Pairs = query.split(/[;&]/); for ( var i = 0; i < Pairs.length; i++ ) { var KeyVal = Pairs[i].split('='); if ( ! KeyVal || KeyVal.length != 2 ) continue; var key = unescape( KeyVal[0] ); var val = unescape( KeyVal[1] ); val = val.replace(/\+/g, ' '); Params[key] = val; } return Params; } function blockEvents(evt) { if(evt.target){ evt.preventDefault(); }else{ evt.returnValue = false; } }
JavaScript
// This file is part of the jQuery formatCurrency Plugin. // // The jQuery formatCurrency Plugin is free software: you can redistribute it // and/or modify it under the terms of the GNU General Public License as published // by the Free Software Foundation, either version 3 of the License, or // (at your option) any later version. // The jQuery formatCurrency Plugin is distributed in the hope that it will // be useful, but WITHOUT ANY WARRANTY; without even the implied warranty // of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the // GNU General Public License for more details. // // You should have received a copy of the GNU General Public License along with // the jQuery formatCurrency Plugin. If not, see <http://www.gnu.org/licenses/>. (function($) { $.formatCurrency = {}; $.formatCurrency.regions = []; // default Region is en $.formatCurrency.regions[''] = { symbol: '', positiveFormat: '%s%n', negativeFormat: '(%s%n)', decimalSymbol: '.', digitGroupSymbol: ',', groupDigits: true }; $.fn.formatCurrency = function(destination, settings) { if (arguments.length == 1 && typeof destination !== "string") { settings = destination; destination = false; } // initialize defaults var defaults = { name: "formatCurrency", colorize: false, region: '', global: true, roundToDecimalPlace: 2, // roundToDecimalPlace: -1; for no rounding; 0 to round to the dollar; 1 for one digit cents; 2 for two digit cents; 3 for three digit cents; ... eventOnDecimalsEntered: false }; // initialize default region defaults = $.extend(defaults, $.formatCurrency.regions['']); // override defaults with settings passed in settings = $.extend(defaults, settings); // check for region setting if (settings.region.length > 0) { settings = $.extend(settings, getRegionOrCulture(settings.region)); } settings.regex = generateRegex(settings); return this.each(function() { $this = $(this); // get number var num = '0'; num = $this[$this.is('input, select, textarea') ? 'val' : 'html'](); //identify '(123)' as a negative number if (num.search('\\(') >= 0) { num = '-' + num; } if (num === '' || (num === '-' && settings.roundToDecimalPlace === -1)) { return; } // if the number is valid use it, otherwise clean it if (isNaN(num)) { // clean number num = num.replace(settings.regex, ''); if (num === '' || (num === '-' && settings.roundToDecimalPlace === -1)) { return; } if (settings.decimalSymbol != '.') { num = num.replace(settings.decimalSymbol, '.'); // reset to US decimal for arithmetic } if (isNaN(num)) { num = '0'; } } // evalutate number input var numParts = String(num).split('.'); var isPositive = (num == Math.abs(num)); var hasDecimals = (numParts.length > 1); var decimals = (hasDecimals ? numParts[1].toString() : '0'); var originalDecimals = decimals; // format number num = Math.abs(numParts[0]); num = isNaN(num) ? 0 : num; if (settings.roundToDecimalPlace >= 0) { decimals = parseFloat('1.' + decimals); // prepend "0."; (IE does NOT round 0.50.toFixed(0) up, but (1+0.50).toFixed(0)-1 decimals = decimals.toFixed(settings.roundToDecimalPlace); // round if (decimals.substring(0, 1) == '2') { num = Number(num) + 1; } decimals = decimals.substring(2); // remove "0." } num = String(num); if (settings.groupDigits) { for (var i = 0; i < Math.floor((num.length - (1 + i)) / 3); i++) { num = num.substring(0, num.length - (4 * i + 3)) + settings.digitGroupSymbol + num.substring(num.length - (4 * i + 3)); } } if ((hasDecimals && settings.roundToDecimalPlace == -1) || settings.roundToDecimalPlace > 0) { num += settings.decimalSymbol + decimals; } // format symbol/negative var format = isPositive ? settings.positiveFormat : settings.negativeFormat; var money = format.replace(/%s/g, settings.symbol); money = money.replace(/%n/g, num); // setup destination var $destination = $([]); if (!destination) { $destination = $this; } else { $destination = $(destination); } // set destination $destination[$destination.is('input, select, textarea') ? 'val' : 'html'](money); if ( hasDecimals && settings.eventOnDecimalsEntered && originalDecimals.length > settings.roundToDecimalPlace ) { $destination.trigger('decimalsEntered', originalDecimals); } // colorize if (settings.colorize) { $destination.css('color', isPositive ? 'black' : 'red'); } }); }; // Remove all non numbers from text $.fn.toNumber = function(settings) { var defaults = $.extend({ name: "toNumber", region: '', global: true }, $.formatCurrency.regions['']); settings = jQuery.extend(defaults, settings); if (settings.region.length > 0) { settings = $.extend(settings, getRegionOrCulture(settings.region)); } settings.regex = generateRegex(settings); return this.each(function() { var method = $(this).is('input, select, textarea') ? 'val' : 'html'; $(this)[method]($(this)[method]().replace('(', '(-').replace(settings.regex, '')); }); }; // returns the value from the first element as a number $.fn.asNumber = function(settings) { var defaults = $.extend({ name: "asNumber", region: '', parse: true, parseType: 'Float', global: true }, $.formatCurrency.regions['']); settings = jQuery.extend(defaults, settings); if (settings.region.length > 0) { settings = $.extend(settings, getRegionOrCulture(settings.region)); } settings.regex = generateRegex(settings); settings.parseType = validateParseType(settings.parseType); var method = $(this).is('input, select, textarea') ? 'val' : 'html'; var num = $(this)[method](); num = num ? num : ""; num = num.replace('(', '(-'); num = num.replace(settings.regex, ''); if (!settings.parse) { return num; } if (num.length == 0) { num = '0'; } if (settings.decimalSymbol != '.') { num = num.replace(settings.decimalSymbol, '.'); // reset to US decimal for arthmetic } return window['parse' + settings.parseType](num); }; function getRegionOrCulture(region) { var regionInfo = $.formatCurrency.regions[region]; if (regionInfo) { return regionInfo; } else { if (/(\w+)-(\w+)/g.test(region)) { var culture = region.replace(/(\w+)-(\w+)/g, "$1"); return $.formatCurrency.regions[culture]; } } // fallback to extend(null) (i.e. nothing) return null; } function validateParseType(parseType) { switch (parseType.toLowerCase()) { case 'int': return 'Int'; case 'float': return 'Float'; default: throw 'invalid parseType'; } } function generateRegex(settings) { if (settings.symbol === '') { return new RegExp("[^\\d" + settings.decimalSymbol + "-]", "g"); } else { var symbol = settings.symbol.replace('$', '\\$').replace('.', '\\.'); return new RegExp(symbol + "|[^\\d" + settings.decimalSymbol + "-]", "g"); } } })(jQuery);
JavaScript
/* * Flexigrid for jQuery - v1.1 * * Copyright (c) 2008 Paulo P. Marinas (code.google.com/p/flexigrid/) * Dual licensed under the MIT or GPL Version 2 licenses. * http://jquery.org/license * */ (function ($) { $.addFlex = function (t, p) { if (t.grid) return false; //return if already exist p = $.extend({ //apply default properties height: 200, //default height width: 'auto', //auto width striped: true, //apply odd even stripes novstripe: false, minwidth: 30, //min width of columns minheight: 80, //min height of columns resizable: true, //allow table resizing url: false, //URL if using data from AJAX method: 'POST', //data sending method dataType: 'xml', //type of data for AJAX, either xml or json errormsg: 'Connection Error', usepager: false, nowrap: true, page: 1, //current page total: 1, //total pages useRp: true, //use the results per page select box rp: 15, //results per page rpOptions: [10, 15, 20, 30, 50], //allowed per-page values title: false, pagestat: 'Displaying {from} to {to} of {total} items', pagetext: 'Page', outof: 'of', findtext: 'Find', procmsg: 'Processing, please wait ...', query: '', qtype: '', nomsg: 'No items', minColToggle: 1, //minimum allowed column to be hidden showToggleBtn: true, //show or hide column toggle popup hideOnSubmit: true, autoload: true, blockOpacity: 0.5, preProcess: false, onDragCol: false, onToggleCol: false, onChangeSort: false, onSuccess: false, onError: false, onSubmit: false //using a custom populate function }, p); $(t).show() //show if hidden .attr({ cellPadding: 0, cellSpacing: 0, border: 0 }) //remove padding and spacing .removeAttr('width'); //remove width properties //create grid class var g = { hset: {}, rePosDrag: function () { var cdleft = 0 - this.hDiv.scrollLeft; if (this.hDiv.scrollLeft > 0) cdleft -= Math.floor(p.cgwidth / 2); $(g.cDrag).css({ top: g.hDiv.offsetTop + 1 }); var cdpad = this.cdpad; $('div', g.cDrag).hide(); $('thead tr:first th:visible', this.hDiv).each(function () { var n = $('thead tr:first th:visible', g.hDiv).index(this); var cdpos = parseInt($('div', this).width()); if (cdleft == 0) cdleft -= Math.floor(p.cgwidth / 2); cdpos = cdpos + cdleft + cdpad; if (isNaN(cdpos)) { cdpos = 0; } $('div:eq(' + n + ')', g.cDrag).css({ 'left': cdpos + 'px' }).show(); cdleft = cdpos; }); }, fixHeight: function (newH) { newH = false; if (!newH) newH = $(g.bDiv).height(); var hdHeight = $(this.hDiv).height(); $('div', this.cDrag).each( function () { $(this).height(newH + hdHeight); } ); var nd = parseInt($(g.nDiv).height()); if (nd > newH) $(g.nDiv).height(newH).width(200); else $(g.nDiv).height('auto').width('auto'); $(g.block).css({ height: newH, marginBottom: (newH * -1) }); var hrH = g.bDiv.offsetTop + newH; if (p.height != 'auto' && p.resizable) hrH = g.vDiv.offsetTop; $(g.rDiv).css({ height: hrH }); }, dragStart: function (dragtype, e, obj) { //default drag function start if (dragtype == 'colresize') {//column resize $(g.nDiv).hide(); $(g.nBtn).hide(); var n = $('div', this.cDrag).index(obj); var ow = $('th:visible div:eq(' + n + ')', this.hDiv).width(); $(obj).addClass('dragging').siblings().hide(); $(obj).prev().addClass('dragging').show(); this.colresize = { startX: e.pageX, ol: parseInt(obj.style.left), ow: ow, n: n }; $('body').css('cursor', 'col-resize'); } else if (dragtype == 'vresize') {//table resize var hgo = false; $('body').css('cursor', 'row-resize'); if (obj) { hgo = true; $('body').css('cursor', 'col-resize'); } this.vresize = { h: p.height, sy: e.pageY, w: p.width, sx: e.pageX, hgo: hgo }; } else if (dragtype == 'colMove') {//column header drag $(g.nDiv).hide(); $(g.nBtn).hide(); this.hset = $(this.hDiv).offset(); this.hset.right = this.hset.left + $('table', this.hDiv).width(); this.hset.bottom = this.hset.top + $('table', this.hDiv).height(); this.dcol = obj; this.dcoln = $('th', this.hDiv).index(obj); this.colCopy = document.createElement("div"); this.colCopy.className = "colCopy"; this.colCopy.innerHTML = obj.innerHTML; if ($.browser.msie) { this.colCopy.className = "colCopy ie"; } $(this.colCopy).css({ position: 'absolute', float: 'left', display: 'none', textAlign: obj.align }); $('body').append(this.colCopy); $(this.cDrag).hide(); } $('body').noSelect(); }, dragMove: function (e) { if (this.colresize) {//column resize var n = this.colresize.n; var diff = e.pageX - this.colresize.startX; var nleft = this.colresize.ol + diff; var nw = this.colresize.ow + diff; if (nw > p.minwidth) { $('div:eq(' + n + ')', this.cDrag).css('left', nleft); this.colresize.nw = nw; } } else if (this.vresize) {//table resize var v = this.vresize; var y = e.pageY; var diff = y - v.sy; if (!p.defwidth) p.defwidth = p.width; if (p.width != 'auto' && !p.nohresize && v.hgo) { var x = e.pageX; var xdiff = x - v.sx; var newW = v.w + xdiff; if (newW > p.defwidth) { this.gDiv.style.width = newW + 'px'; p.width = newW; } } var newH = v.h + diff; if ((newH > p.minheight || p.height < p.minheight) && !v.hgo) { this.bDiv.style.height = newH + 'px'; p.height = newH; this.fixHeight(newH); } v = null; } else if (this.colCopy) { $(this.dcol).addClass('thMove').removeClass('thOver'); if (e.pageX > this.hset.right || e.pageX < this.hset.left || e.pageY > this.hset.bottom || e.pageY < this.hset.top) { //this.dragEnd(); $('body').css('cursor', 'move'); } else { $('body').css('cursor', 'pointer'); } $(this.colCopy).css({ top: e.pageY + 10, left: e.pageX + 20, display: 'block' }); } }, dragEnd: function () { if (this.colresize) { var n = this.colresize.n; var nw = this.colresize.nw; $('th:visible div:eq(' + n + ')', this.hDiv).css('width', nw); $('tr', this.bDiv).each( function () { $('td:visible div:eq(' + n + ')', this).css('width', nw); } ); this.hDiv.scrollLeft = this.bDiv.scrollLeft; $('div:eq(' + n + ')', this.cDrag).siblings().show(); $('.dragging', this.cDrag).removeClass('dragging'); this.rePosDrag(); this.fixHeight(); this.colresize = false; } else if (this.vresize) { this.vresize = false; } else if (this.colCopy) { $(this.colCopy).remove(); if (this.dcolt != null) { if (this.dcoln > this.dcolt) $('th:eq(' + this.dcolt + ')', this.hDiv).before(this.dcol); else $('th:eq(' + this.dcolt + ')', this.hDiv).after(this.dcol); this.switchCol(this.dcoln, this.dcolt); $(this.cdropleft).remove(); $(this.cdropright).remove(); this.rePosDrag(); if (p.onDragCol) { p.onDragCol(this.dcoln, this.dcolt); } } this.dcol = null; this.hset = null; this.dcoln = null; this.dcolt = null; this.colCopy = null; $('.thMove', this.hDiv).removeClass('thMove'); $(this.cDrag).show(); } $('body').css('cursor', 'default'); $('body').noSelect(false); }, toggleCol: function (cid, visible) { var ncol = $("th[axis='col" + cid + "']", this.hDiv)[0]; var n = $('thead th', g.hDiv).index(ncol); var cb = $('input[value=' + cid + ']', g.nDiv)[0]; if (visible == null) { visible = ncol.hidden; } if ($('input:checked', g.nDiv).length < p.minColToggle && !visible) { return false; } if (visible) { ncol.hidden = false; $(ncol).show(); cb.checked = true; } else { ncol.hidden = true; $(ncol).hide(); cb.checked = false; } $('tbody tr', t).each( function () { if (visible) { $('td:eq(' + n + ')', this).show(); } else { $('td:eq(' + n + ')', this).hide(); } } ); this.rePosDrag(); if (p.onToggleCol) { p.onToggleCol(cid, visible); } return visible; }, switchCol: function (cdrag, cdrop) { //switch columns $('tbody tr', t).each( function () { if (cdrag > cdrop) $('td:eq(' + cdrop + ')', this).before($('td:eq(' + cdrag + ')', this)); else $('td:eq(' + cdrop + ')', this).after($('td:eq(' + cdrag + ')', this)); } ); //switch order in nDiv if (cdrag > cdrop) { $('tr:eq(' + cdrop + ')', this.nDiv).before($('tr:eq(' + cdrag + ')', this.nDiv)); } else { $('tr:eq(' + cdrop + ')', this.nDiv).after($('tr:eq(' + cdrag + ')', this.nDiv)); } if ($.browser.msie && $.browser.version < 7.0) { $('tr:eq(' + cdrop + ') input', this.nDiv)[0].checked = true; } this.hDiv.scrollLeft = this.bDiv.scrollLeft; }, scroll: function () { this.hDiv.scrollLeft = this.bDiv.scrollLeft; this.rePosDrag(); }, addData: function (data) { //parse data if (p.dataType == 'json') { data = $.extend({rows: [], page: 0, total: 0}, data); } if (p.preProcess) { data = p.preProcess(data); } $('.pReload', this.pDiv).removeClass('loading'); this.loading = false; if (!data) { $('.pPageStat', this.pDiv).html(p.errormsg); return false; } if (p.dataType == 'xml') { p.total = +$('rows total', data).text(); } else { p.total = data.total; } if (p.total == 0) { $('tr, a, td, div', t).unbind(); $(t).empty(); p.pages = 1; p.page = 1; this.buildpager(); $('.pPageStat', this.pDiv).html(p.nomsg); return false; } p.pages = Math.ceil(p.total / p.rp); if (p.dataType == 'xml') { p.page = +$('rows page', data).text(); } else { p.page = data.page; } this.buildpager(); //build new body var tbody = document.createElement('tbody'); if (p.dataType == 'json') { $.each(data.rows, function (i, row) { var tr = document.createElement('tr'); if (i % 2 && p.striped) { tr.className = 'erow'; } if (row.id) { tr.id = 'row' + row.id; } $('thead tr:first th', g.hDiv).each( //add cell function () { var td = document.createElement('td'); var idx = $(this).attr('axis').substr(3); td.align = this.align; // If the json elements aren't named (which is typical), use numeric order if (typeof row.cell[idx] != "undefined") { td.innerHTML = (row.cell[idx] != null) ? row.cell[idx] : '';//null-check for Opera-browser } else { td.innerHTML = row.cell[p.colModel[idx].name]; } $(td).attr('abbr', $(this).attr('abbr')); $(tr).append(td); td = null; } ); if ($('thead', this.gDiv).length < 1) {//handle if grid has no headers for (idx = 0; idx < cell.length; idx++) { var td = document.createElement('td'); // If the json elements aren't named (which is typical), use numeric order if (typeof row.cell[idx] != "undefined") { td.innerHTML = (row.cell[idx] != null) ? row.cell[idx] : '';//null-check for Opera-browser } else { td.innerHTML = row.cell[p.colModel[idx].name]; } $(tr).append(td); td = null; } } $(tbody).append(tr); tr = null; }); } else if (p.dataType == 'xml') { var i = 1; $("rows row", data).each(function () { i++; var tr = document.createElement('tr'); if (i % 2 && p.striped) { tr.className = 'erow'; } var nid = $(this).attr('id'); if (nid) { tr.id = 'row' + nid; } nid = null; var robj = this; $('thead tr:first th', g.hDiv).each(function () { var td = document.createElement('td'); var idx = $(this).attr('axis').substr(3); td.align = this.align; td.innerHTML = $("cell:eq(" + idx + ")", robj).text(); $(td).attr('abbr', $(this).attr('abbr')); $(tr).append(td); td = null; }); if ($('thead', this.gDiv).length < 1) {//handle if grid has no headers $('cell', this).each(function () { var td = document.createElement('td'); td.innerHTML = $(this).text(); $(tr).append(td); td = null; }); } $(tbody).append(tr); tr = null; robj = null; }); } $('tr', t).unbind(); $(t).empty(); $(t).append(tbody); this.addCellProp(); this.addRowProp(); this.rePosDrag(); tbody = null; data = null; i = null; if (p.onSuccess) { p.onSuccess(this); } if (p.hideOnSubmit) { $(g.block).remove(); } this.hDiv.scrollLeft = this.bDiv.scrollLeft; if ($.browser.opera) { $(t).css('visibility', 'visible'); } }, changeSort: function (th) { //change sortorder if (this.loading) { return true; } $(g.nDiv).hide(); $(g.nBtn).hide(); if (p.sortname == $(th).attr('abbr')) { if (p.sortorder == 'asc') { p.sortorder = 'desc'; } else { p.sortorder = 'asc'; } } $(th).addClass('sorted').siblings().removeClass('sorted'); $('.sdesc', this.hDiv).removeClass('sdesc'); $('.sasc', this.hDiv).removeClass('sasc'); $('div', th).addClass('s' + p.sortorder); p.sortname = $(th).attr('abbr'); if (p.onChangeSort) { p.onChangeSort(p.sortname, p.sortorder); } else { this.populate(); } }, buildpager: function () { //rebuild pager based on new properties $('.pcontrol input', this.pDiv).val(p.page); $('.pcontrol span', this.pDiv).html(p.pages); var r1 = (p.page - 1) * p.rp + 1; var r2 = r1 + p.rp - 1; if (p.total < r2) { r2 = p.total; } var stat = p.pagestat; stat = stat.replace(/{from}/, r1); stat = stat.replace(/{to}/, r2); stat = stat.replace(/{total}/, p.total); $('.pPageStat', this.pDiv).html(stat); }, populate: function () { //get latest data if (this.loading) { return true; } if (p.onSubmit) { var gh = p.onSubmit(); if (!gh) { return false; } } this.loading = true; if (!p.url) { return false; } $('.pPageStat', this.pDiv).html(p.procmsg); $('.pReload', this.pDiv).addClass('loading'); $(g.block).css({ top: g.bDiv.offsetTop }); if (p.hideOnSubmit) { $(this.gDiv).prepend(g.block); } if ($.browser.opera) { $(t).css('visibility', 'hidden'); } if (!p.newp) { p.newp = 1; } if (p.page > p.pages) { p.page = p.pages; } var param = [{ name: 'page', value: p.newp }, { name: 'rp', value: p.rp }, { name: 'sortname', value: p.sortname }, { name: 'sortorder', value: p.sortorder }, { name: 'query', value: p.query }, { name: 'qtype', value: p.qtype }]; if (p.params) { for (var pi = 0; pi < p.params.length; pi++) { param[param.length] = p.params[pi]; } } $.ajax({ type: p.method, url: p.url, data: param, dataType: p.dataType, success: function (data) { g.addData(data); }, error: function (XMLHttpRequest, textStatus, errorThrown) { try { if (p.onError) p.onError(XMLHttpRequest, textStatus, errorThrown); } catch (e) {} } }); }, doSearch: function () { p.query = $('input[name=q]', g.sDiv).val(); p.qtype = $('select[name=qtype]', g.sDiv).val(); p.newp = 1; this.populate(); }, changePage: function (ctype) { //change page if (this.loading) { return true; } switch (ctype) { case 'first': p.newp = 1; break; case 'prev': if (p.page > 1) { p.newp = parseInt(p.page) - 1; } break; case 'next': if (p.page < p.pages) { p.newp = parseInt(p.page) + 1; } break; case 'last': p.newp = p.pages; break; case 'input': var nv = parseInt($('.pcontrol input', this.pDiv).val()); if (isNaN(nv)) { nv = 1; } if (nv < 1) { nv = 1; } else if (nv > p.pages) { nv = p.pages; } $('.pcontrol input', this.pDiv).val(nv); p.newp = nv; break; } if (p.newp == p.page) { return false; } if (p.onChangePage) { p.onChangePage(p.newp); } else { this.populate(); } }, addCellProp: function () { $('tbody tr td', g.bDiv).each(function () { var tdDiv = document.createElement('div'); var n = $('td', $(this).parent()).index(this); var pth = $('th:eq(' + n + ')', g.hDiv).get(0); if (pth != null) { if (p.sortname == $(pth).attr('abbr') && p.sortname) { this.className = 'sorted'; } $(tdDiv).css({ textAlign: pth.align, width: $('div:first', pth)[0].style.width }); if (pth.hidden) { $(this).css('display', 'none'); } } if (p.nowrap == false) { $(tdDiv).css('white-space', 'normal'); } if (this.innerHTML == '') { this.innerHTML = '&nbsp;'; } tdDiv.innerHTML = this.innerHTML; var prnt = $(this).parent()[0]; var pid = false; if (prnt.id) { pid = prnt.id.substr(3); } if (pth != null) { if (pth.process) pth.process(tdDiv, pid); } $(this).empty().append(tdDiv).removeAttr('width'); //wrap content }); }, getCellDim: function (obj) {// get cell prop for editable event var ht = parseInt($(obj).height()); var pht = parseInt($(obj).parent().height()); var wt = parseInt(obj.style.width); var pwt = parseInt($(obj).parent().width()); var top = obj.offsetParent.offsetTop; var left = obj.offsetParent.offsetLeft; var pdl = parseInt($(obj).css('paddingLeft')); var pdt = parseInt($(obj).css('paddingTop')); return { ht: ht, wt: wt, top: top, left: left, pdl: pdl, pdt: pdt, pht: pht, pwt: pwt }; }, addRowProp: function () { $('tbody tr', g.bDiv).each(function () { $(this).click(function (e) { var obj = (e.target || e.srcElement); if (obj.href || obj.type) return true; $(this).toggleClass('trSelected'); if (p.singleSelect) $(this).siblings().removeClass('trSelected'); }).mousedown(function (e) { if (e.shiftKey) { $(this).toggleClass('trSelected'); g.multisel = true; this.focus(); $(g.gDiv).noSelect(); } }).mouseup(function () { if (g.multisel) { g.multisel = false; $(g.gDiv).noSelect(false); } }).hover(function (e) { if (g.multisel) { $(this).toggleClass('trSelected'); } }, function () {}); if ($.browser.msie && $.browser.version < 7.0) { $(this).hover(function () { $(this).addClass('trOver'); }, function () { $(this).removeClass('trOver'); }); } }); }, pager: 0 }; if (p.colModel) { //create model if any thead = document.createElement('thead'); var tr = document.createElement('tr'); for (var i = 0; i < p.colModel.length; i++) { var cm = p.colModel[i]; var th = document.createElement('th'); th.innerHTML = cm.display; if (cm.name && cm.sortable) { $(th).attr('abbr', cm.name); } $(th).attr('axis', 'col' + i); if (cm.align) { th.align = cm.align; } if (cm.width) { $(th).attr('width', cm.width); } if ($(cm).attr('hide')) { th.hidden = true; } if (cm.process) { th.process = cm.process; } $(tr).append(th); } $(thead).append(tr); $(t).prepend(thead); } // end if p.colmodel //init divs g.gDiv = document.createElement('div'); //create global container g.mDiv = document.createElement('div'); //create title container g.hDiv = document.createElement('div'); //create header container g.bDiv = document.createElement('div'); //create body container g.vDiv = document.createElement('div'); //create grip g.rDiv = document.createElement('div'); //create horizontal resizer g.cDrag = document.createElement('div'); //create column drag g.block = document.createElement('div'); //creat blocker g.nDiv = document.createElement('div'); //create column show/hide popup g.nBtn = document.createElement('div'); //create column show/hide button g.iDiv = document.createElement('div'); //create editable layer g.tDiv = document.createElement('div'); //create toolbar g.sDiv = document.createElement('div'); g.pDiv = document.createElement('div'); //create pager container if (!p.usepager) { g.pDiv.style.display = 'none'; } g.hTable = document.createElement('table'); g.gDiv.className = 'flexigrid'; if (p.width != 'auto') { g.gDiv.style.width = p.width + 'px'; } //add conditional classes if ($.browser.msie) { $(g.gDiv).addClass('ie'); } if (p.novstripe) { $(g.gDiv).addClass('novstripe'); } $(t).before(g.gDiv); $(g.gDiv).append(t); //set toolbar if (p.buttons) { g.tDiv.className = 'tDiv'; var tDiv2 = document.createElement('div'); tDiv2.className = 'tDiv2'; for (var i = 0; i < p.buttons.length; i++) { var btn = p.buttons[i]; if (!btn.separator) { var btnDiv = document.createElement('div'); btnDiv.className = 'fbutton'; btnDiv.innerHTML = "<div><span>" + btn.name + "</span></div>"; if (btn.bclass) $('span', btnDiv).addClass(btn.bclass).css({ paddingLeft: 20 }); btnDiv.onpress = btn.onpress; btnDiv.name = btn.name; if (btn.onpress) { $(btnDiv).click(function () { this.onpress(this.name, g.gDiv); }); } $(tDiv2).append(btnDiv); if ($.browser.msie && $.browser.version < 7.0) { $(btnDiv).hover(function () { $(this).addClass('fbOver'); }, function () { $(this).removeClass('fbOver'); }); } } else { $(tDiv2).append("<div class='btnseparator'></div>"); } } $(g.tDiv).append(tDiv2); $(g.tDiv).append("<div style='clear:both'></div>"); $(g.gDiv).prepend(g.tDiv); } g.hDiv.className = 'hDiv'; $(t).before(g.hDiv); g.hTable.cellPadding = 0; g.hTable.cellSpacing = 0; $(g.hDiv).append('<div class="hDivBox"></div>'); $('div', g.hDiv).append(g.hTable); var thead = $("thead:first", t).get(0); if (thead) $(g.hTable).append(thead); thead = null; if (!p.colmodel) var ci = 0; $('thead tr:first th', g.hDiv).each(function () { var thdiv = document.createElement('div'); if ($(this).attr('abbr')) { $(this).click(function (e) { if (!$(this).hasClass('thOver')) return false; var obj = (e.target || e.srcElement); if (obj.href || obj.type) return true; g.changeSort(this); }); if ($(this).attr('abbr') == p.sortname) { this.className = 'sorted'; thdiv.className = 's' + p.sortorder; } } if (this.hidden) { $(this).hide(); } if (!p.colmodel) { $(this).attr('axis', 'col' + ci++); } $(thdiv).css({ textAlign: this.align, width: this.width + 'px' }); thdiv.innerHTML = this.innerHTML; $(this).empty().append(thdiv).removeAttr('width').mousedown(function (e) { g.dragStart('colMove', e, this); }).hover(function () { if (!g.colresize && !$(this).hasClass('thMove') && !g.colCopy) { $(this).addClass('thOver'); } if ($(this).attr('abbr') != p.sortname && !g.colCopy && !g.colresize && $(this).attr('abbr')) { $('div', this).addClass('s' + p.sortorder); } else if ($(this).attr('abbr') == p.sortname && !g.colCopy && !g.colresize && $(this).attr('abbr')) { var no = (p.sortorder == 'asc') ? 'desc' : 'asc'; $('div', this).removeClass('s' + p.sortorder).addClass('s' + no); } if (g.colCopy) { var n = $('th', g.hDiv).index(this); if (n == g.dcoln) { return false; } if (n < g.dcoln) { $(this).append(g.cdropleft); } else { $(this).append(g.cdropright); } g.dcolt = n; } else if (!g.colresize) { var nv = $('th:visible', g.hDiv).index(this); var onl = parseInt($('div:eq(' + nv + ')', g.cDrag).css('left')); var nw = jQuery(g.nBtn).outerWidth(); var nl = onl - nw + Math.floor(p.cgwidth / 2); $(g.nDiv).hide(); $(g.nBtn).hide(); $(g.nBtn).css({ 'left': nl, top: g.hDiv.offsetTop }).show(); var ndw = parseInt($(g.nDiv).width()); $(g.nDiv).css({ top: g.bDiv.offsetTop }); if ((nl + ndw) > $(g.gDiv).width()) { $(g.nDiv).css('left', onl - ndw + 1); } else { $(g.nDiv).css('left', nl); } if ($(this).hasClass('sorted')) { $(g.nBtn).addClass('srtd'); } else { $(g.nBtn).removeClass('srtd'); } } }, function () { $(this).removeClass('thOver'); if ($(this).attr('abbr') != p.sortname) { $('div', this).removeClass('s' + p.sortorder); } else if ($(this).attr('abbr') == p.sortname) { var no = (p.sortorder == 'asc') ? 'desc' : 'asc'; $('div', this).addClass('s' + p.sortorder).removeClass('s' + no); } if (g.colCopy) { $(g.cdropleft).remove(); $(g.cdropright).remove(); g.dcolt = null; } }); //wrap content }); //set bDiv g.bDiv.className = 'bDiv'; $(t).before(g.bDiv); $(g.bDiv).css({ height: (p.height == 'auto') ? 'auto' : p.height + "px" }).scroll(function (e) { g.scroll() }).append(t); if (p.height == 'auto') { $('table', g.bDiv).addClass('autoht'); } //add td & row properties g.addCellProp(); g.addRowProp(); //set cDrag var cdcol = $('thead tr:first th:first', g.hDiv).get(0); if (cdcol != null) { g.cDrag.className = 'cDrag'; g.cdpad = 0; g.cdpad += (isNaN(parseInt($('div', cdcol).css('borderLeftWidth'))) ? 0 : parseInt($('div', cdcol).css('borderLeftWidth'))); g.cdpad += (isNaN(parseInt($('div', cdcol).css('borderRightWidth'))) ? 0 : parseInt($('div', cdcol).css('borderRightWidth'))); g.cdpad += (isNaN(parseInt($('div', cdcol).css('paddingLeft'))) ? 0 : parseInt($('div', cdcol).css('paddingLeft'))); g.cdpad += (isNaN(parseInt($('div', cdcol).css('paddingRight'))) ? 0 : parseInt($('div', cdcol).css('paddingRight'))); g.cdpad += (isNaN(parseInt($(cdcol).css('borderLeftWidth'))) ? 0 : parseInt($(cdcol).css('borderLeftWidth'))); g.cdpad += (isNaN(parseInt($(cdcol).css('borderRightWidth'))) ? 0 : parseInt($(cdcol).css('borderRightWidth'))); g.cdpad += (isNaN(parseInt($(cdcol).css('paddingLeft'))) ? 0 : parseInt($(cdcol).css('paddingLeft'))); g.cdpad += (isNaN(parseInt($(cdcol).css('paddingRight'))) ? 0 : parseInt($(cdcol).css('paddingRight'))); $(g.bDiv).before(g.cDrag); var cdheight = $(g.bDiv).height(); var hdheight = $(g.hDiv).height(); $(g.cDrag).css({ top: -hdheight + 'px' }); $('thead tr:first th', g.hDiv).each(function () { var cgDiv = document.createElement('div'); $(g.cDrag).append(cgDiv); if (!p.cgwidth) { p.cgwidth = $(cgDiv).width(); } $(cgDiv).css({ height: cdheight + hdheight }).mousedown(function (e) { g.dragStart('colresize', e, this); }); if ($.browser.msie && $.browser.version < 7.0) { g.fixHeight($(g.gDiv).height()); $(cgDiv).hover(function () { g.fixHeight(); $(this).addClass('dragging') }, function () { if (!g.colresize) $(this).removeClass('dragging') }); } }); } //add strip if (p.striped) { $('tbody tr:odd', g.bDiv).addClass('erow'); } if (p.resizable && p.height != 'auto') { g.vDiv.className = 'vGrip'; $(g.vDiv).mousedown(function (e) { g.dragStart('vresize', e) }).html('<span></span>'); $(g.bDiv).after(g.vDiv); } if (p.resizable && p.width != 'auto' && !p.nohresize) { g.rDiv.className = 'hGrip'; $(g.rDiv).mousedown(function (e) { g.dragStart('vresize', e, true); }).html('<span></span>').css('height', $(g.gDiv).height()); if ($.browser.msie && $.browser.version < 7.0) { $(g.rDiv).hover(function () { $(this).addClass('hgOver'); }, function () { $(this).removeClass('hgOver'); }); } $(g.gDiv).append(g.rDiv); } // add pager if (p.usepager) { g.pDiv.className = 'pDiv'; g.pDiv.innerHTML = '<div class="pDiv2"></div>'; $(g.bDiv).after(g.pDiv); var html = ' <div class="pGroup"> <div class="pFirst pButton"><span></span></div><div class="pPrev pButton"><span></span></div> </div> <div class="btnseparator"></div> <div class="pGroup"><span class="pcontrol">' + p.pagetext + ' <input type="text" size="4" value="1" /> ' + p.outof + ' <span> 1 </span></span></div> <div class="btnseparator"></div> <div class="pGroup"> <div class="pNext pButton"><span></span></div><div class="pLast pButton"><span></span></div> </div> <div class="btnseparator"></div> <div class="pGroup"> <div class="pReload pButton"><span></span></div> </div> <div class="btnseparator"></div> <div class="pGroup"><span class="pPageStat"></span></div>'; $('div', g.pDiv).html(html); $('.pReload', g.pDiv).click(function () { g.populate() }); $('.pFirst', g.pDiv).click(function () { g.changePage('first') }); $('.pPrev', g.pDiv).click(function () { g.changePage('prev') }); $('.pNext', g.pDiv).click(function () { g.changePage('next') }); $('.pLast', g.pDiv).click(function () { g.changePage('last') }); $('.pcontrol input', g.pDiv).keydown(function (e) { if (e.keyCode == 13) g.changePage('input') }); if ($.browser.msie && $.browser.version < 7) $('.pButton', g.pDiv).hover(function () { $(this).addClass('pBtnOver'); }, function () { $(this).removeClass('pBtnOver'); }); if (p.useRp) { var opt = '', sel = ''; for (var nx = 0; nx < p.rpOptions.length; nx++) { if (p.rp == p.rpOptions[nx]) sel = 'selected="selected"'; else sel = ''; opt += "<option value='" + p.rpOptions[nx] + "' " + sel + " >" + p.rpOptions[nx] + "&nbsp;&nbsp;</option>"; } $('.pDiv2', g.pDiv).prepend("<div class='pGroup'><select name='rp'>" + opt + "</select></div> <div class='btnseparator'></div>"); $('select', g.pDiv).change(function () { if (p.onRpChange) { p.onRpChange(+this.value); } else { p.newp = 1; p.rp = +this.value; g.populate(); } }); } //add search button if (p.searchitems) { $('.pDiv2', g.pDiv).prepend("<div class='pGroup'> <div class='pSearch pButton'><span></span></div> </div> <div class='btnseparator'></div>"); $('.pSearch', g.pDiv).click(function () { $(g.sDiv).slideToggle('fast', function () { $('.sDiv:visible input:first', g.gDiv).trigger('focus'); }); }); //add search box g.sDiv.className = 'sDiv'; var sitems = p.searchitems; var sopt = '', sel = ''; for (var s = 0; s < sitems.length; s++) { if (p.qtype == '' && sitems[s].isdefault == true) { p.qtype = sitems[s].name; sel = 'selected="selected"'; } else { sel = ''; } sopt += "<option value='" + sitems[s].name + "' " + sel + " >" + sitems[s].display + "&nbsp;&nbsp;</option>"; } if (p.qtype == '') { p.qtype = sitems[0].name; } $(g.sDiv).append("<div class='sDiv2'>" + p.findtext + " <input type='text' value='" + p.query +"' size='30' name='q' class='qsbox' /> "+ " <select name='qtype'>" + sopt + "</select></div>"); //Split into separate selectors because of bug in jQuery 1.3.2 $('input[name=q]', g.sDiv).keydown(function (e) { if (e.keyCode == 13) { g.doSearch(); } }); $('select[name=qtype]', g.sDiv).keydown(function (e) { if (e.keyCode == 13) { g.doSearch(); } }); $('input[value=Clear]', g.sDiv).click(function () { $('input[name=q]', g.sDiv).val(''); p.query = ''; g.doSearch(); }); $(g.bDiv).after(g.sDiv); } } $(g.pDiv, g.sDiv).append("<div style='clear:both'></div>"); // add title if (p.title) { g.mDiv.className = 'mDiv'; g.mDiv.innerHTML = '<div class="ftitle">' + p.title + '</div>'; $(g.gDiv).prepend(g.mDiv); if (p.showTableToggleBtn) { $(g.mDiv).append('<div class="ptogtitle" title="Minimize/Maximize Table"><span></span></div>'); $('div.ptogtitle', g.mDiv).click(function () { $(g.gDiv).toggleClass('hideBody'); $(this).toggleClass('vsble'); }); } } //setup cdrops g.cdropleft = document.createElement('span'); g.cdropleft.className = 'cdropleft'; g.cdropright = document.createElement('span'); g.cdropright.className = 'cdropright'; //add block g.block.className = 'gBlock'; var gh = $(g.bDiv).height(); var gtop = g.bDiv.offsetTop; $(g.block).css({ width: g.bDiv.style.width, height: gh, background: 'white', position: 'relative', marginBottom: (gh * -1), zIndex: 1, top: gtop, left: '0px' }); $(g.block).fadeTo(0, p.blockOpacity); // add column control if ($('th', g.hDiv).length) { g.nDiv.className = 'nDiv'; g.nDiv.innerHTML = "<table cellpadding='0' cellspacing='0'><tbody></tbody></table>"; $(g.nDiv).css({ marginBottom: (gh * -1), display: 'none', top: gtop }).noSelect(); var cn = 0; $('th div', g.hDiv).each(function () { var kcol = $("th[axis='col" + cn + "']", g.hDiv)[0]; var chk = 'checked="checked"'; if (kcol.style.display == 'none') { chk = ''; } $('tbody', g.nDiv).append('<tr><td class="ndcol1"><input type="checkbox" ' + chk + ' class="togCol" value="' + cn + '" /></td><td class="ndcol2">' + this.innerHTML + '</td></tr>'); cn++; }); if ($.browser.msie && $.browser.version < 7.0) $('tr', g.nDiv).hover(function () { $(this).addClass('ndcolover'); }, function () { $(this).removeClass('ndcolover'); }); $('td.ndcol2', g.nDiv).click(function () { if ($('input:checked', g.nDiv).length <= p.minColToggle && $(this).prev().find('input')[0].checked) return false; return g.toggleCol($(this).prev().find('input').val()); }); $('input.togCol', g.nDiv).click(function () { if ($('input:checked', g.nDiv).length < p.minColToggle && this.checked == false) return false; $(this).parent().next().trigger('click'); }); $(g.gDiv).prepend(g.nDiv); $(g.nBtn).addClass('nBtn') .html('<div></div>') .attr('title', 'Hide/Show Columns') .click(function () { $(g.nDiv).toggle(); return true; } ); if (p.showToggleBtn) { $(g.gDiv).prepend(g.nBtn); } } // add date edit layer $(g.iDiv).addClass('iDiv').css({ display: 'none' }); $(g.bDiv).append(g.iDiv); // add flexigrid events $(g.bDiv).hover(function () { $(g.nDiv).hide(); $(g.nBtn).hide(); }, function () { if (g.multisel) { g.multisel = false; } }); $(g.gDiv).hover(function () {}, function () { $(g.nDiv).hide(); $(g.nBtn).hide(); }); //add document events $(document).mousemove(function (e) { g.dragMove(e) }).mouseup(function (e) { g.dragEnd() }).hover(function () {}, function () { g.dragEnd() }); //browser adjustments if ($.browser.msie && $.browser.version < 7.0) { $('.hDiv,.bDiv,.mDiv,.pDiv,.vGrip,.tDiv, .sDiv', g.gDiv).css({ width: '100%' }); $(g.gDiv).addClass('ie6'); if (p.width != 'auto') { $(g.gDiv).addClass('ie6fullwidthbug'); } } g.rePosDrag(); g.fixHeight(); //make grid functions accessible t.p = p; t.grid = g; // load data if (p.url && p.autoload) { g.populate(); } return t; }; var docloaded = false; $(document).ready(function () { docloaded = true }); $.fn.flexigrid = function (p) { return this.each(function () { if (!docloaded) { $(this).hide(); var t = this; $(document).ready(function () { $.addFlex(t, p); }); } else { $.addFlex(this, p); } }); }; //end flexigrid $.fn.flexReload = function (p) { // function to reload grid return this.each(function () { if (this.grid && this.p.url) this.grid.populate(); }); }; //end flexReload $.fn.flexOptions = function (p) { //function to update general options return this.each(function () { if (this.grid) $.extend(this.p, p); }); }; //end flexOptions $.fn.flexToggleCol = function (cid, visible) { // function to reload grid return this.each(function () { if (this.grid) this.grid.toggleCol(cid, visible); }); }; //end flexToggleCol $.fn.flexAddData = function (data) { // function to add data to grid return this.each(function () { if (this.grid) this.grid.addData(data); }); }; $.fn.noSelect = function (p) { //no select plugin by me :-) var prevent = (p == null) ? true : p; if (prevent) { return this.each(function () { if ($.browser.msie || $.browser.safari) $(this).bind('selectstart', function () { return false; }); else if ($.browser.mozilla) { $(this).css('MozUserSelect', 'none'); $('body').trigger('focus'); } else if ($.browser.opera) $(this).bind('mousedown', function () { return false; }); else $(this).attr('unselectable', 'on'); }); } else { return this.each(function () { if ($.browser.msie || $.browser.safari) $(this).unbind('selectstart'); else if ($.browser.mozilla) $(this).css('MozUserSelect', 'inherit'); else if ($.browser.opera) $(this).unbind('mousedown'); else $(this).removeAttr('unselectable', 'on'); }); } }; //end noSelect })(jQuery);
JavaScript
/*! * ExColor for jQuery * http://excolor.ramiro.mx/ */ jQuery.fn.excolor = function (C) { var C = jQuery.extend({ hue_bar: 0, hue_slider: 0, sb_slider: 0, color_box: true, demo_mode: false, show_color_on_border: false, border_color: 'black', sb_border_color: 'black', anim_speed: 'slow', round_corners: true, shadow: true, shadow_size: 4, shadow_color: '#8a8a8a', background_color: 'silver', backlight: true, input_text_color: 'black', input_background_color: 'white', label_color: 'black', effect: 'none', root_path: false, rgb_output: false, callback_on_ok: function () { var a = '' } }, C); return this.each(function () { var j = 'mel', moved_slider = 'mel', correct_x = 0, correct_y = 0, pos_sel = 0, pos_slider = 0, huebox = 0, wrapper = 0, pos_wrap = 0, pos_huebox = 0, hue = 0, sbbox = 0, sb_sel = 0, saturation = 1, brightness = 1, slider = 0, colsample = 0, inp_r = 0, inp_g = 0, inp_b = 0, inp_hex = 0, hexto = 0, ok_but = 0, close_but = 0, aitem = this, aitem_pos = jQuery(this).offset(), opened = false, isample = 0, click_flag = 0, click_to = 0, userok = false, parsex = '', inputhex = '', rgb_input = /\d+\,\d+\,\d+/i, rgb_output = C.rgb_output, looper = 0, switcher = 0; moved_slider = jQuery('script'); if (!C.root_path) { for (var i = 0; i < moved_slider.length; i++) { j = '' + jQuery(moved_slider[i]).attr('src'); j = j.toLowerCase(); j = j.split('jquery.excolor.js'); if (j.length == 2) { root_path = j[0] console.log(root_path); } } } else { root_path = C.root_path; } var k = new Image(); var l = new Image(); var m = new Image(); var n = new Image(); var o = new Image(); var p = new Image(); var q = new Image(); var t = new Image(); k.src = root_path + 'sel.gif'; l.src = root_path + 'slider.gif'; m.src = root_path + 'bg.png'; n.src = root_path + 'hue.png'; o.src = root_path + 'ok.png'; p.src = root_path + 'shbg.png'; q.src = root_path + 'transp0.gif'; t.src = root_path + 'transp.gif'; moved_slider = 'mel'; j = 'mel'; jQuery(aitem).mouseenter(function () { clearTimeout(click_to); click_to = setTimeout(function () { click_flag = true }, 100) }).mouseleave(function () { clearTimeout(click_to); click_to = setTimeout(function () { click_flag = false }, 100) }); if (C.color_box) { jQuery(aitem).wrap('<span style="margin:0;padding:0 ' + jQuery(aitem).outerHeight() + 'px 0 0;display:inline-block;border:none;background:none;line-height:auto;"></span>') } var u = '', rad3px = '', radwrap = '', shadow = '', backlight = ''; if (C.round_corners) { u = '-khtml-border-radius:2px;-moz-border-radius:2px;-webkit-border-radius:2px;border-radius:2px;'; rad3px = '-khtml-border-radius:2px;-moz-border-radius:2px;-webkit-border-radius:2px;border-radius:2px;'; radwrap = '-khtml-border-radius: 0 2px 2px 2px;-moz-border-radius: 0 2px 2px 2px;-webkit-border-radius: 0 2px 2px 2px;border-radius: 0 2px 2px 2px;' } if (C.shadow) { shadow = 'box-shadow:0 ' + C.shadow_size + 'px ' + (C.shadow_size * 2) + 'px 0 ' + C.shadow_color + ';-webkit-box-shadow:0 ' + C.shadow_size + 'px ' + (C.shadow_size * 2) + 'px 0 ' + C.shadow_color + ';-moz-box-shadow:0 ' + C.shadow_size + 'px ' + (C.shadow_size * 2) + 'px 0 ' + C.shadow_color + ';' } if (C.backlight) { backlight = 'background-position:0 0;background-repeat:no-repeat;background-image:url(' + root_path + 'shbg.png);' } var w = new Array(0, 1, 2, 3, 4, 5, 6, 7, 8, 9); w[8] = 8; w[46] = 46; var y = new Array(); y['0'] = 1; y['1'] = 1; y['2'] = 1; y['3'] = 1; y['4'] = 1; y['5'] = 1; y['6'] = 1; y['7'] = 1; y['8'] = 1; y['9'] = 1; y['A'] = 1; y['B'] = 1; y['C'] = 1; y['D'] = 1; y['E'] = 1; y['F'] = 1; y['a'] = 1; y['b'] = 1; y['c'] = 1; y['d'] = 1; y['e'] = 1; y['f'] = 1; var z = new Array(); z[0] = 'system keys'; z[8] = 'backspace'; z[118] = 'ctrl v'; z[86] = 'ctrl v'; z[99] = 'ctrl c'; z[67] = 'ctrl c'; var A = ' ' + Math.random(); A = A.split('.'); A = 'mc' + A[1]; var B = jQuery(aitem).parent().offset(); jQuery(aitem).parent().append('&nbsp;<input class="excolor_clrbox" readonly="readonly" id="' + A + '" type="text" style="display:none;cursor:pointer;width:' + (jQuery(aitem).outerHeight() - 4) + 'px;height:' + (jQuery(aitem).outerHeight() - 4) + 'px;background:none;' + rad3px + 'border:1px solid ' + C.border_color + ';" />'); jQuery(aitem).clone().show().addClass('mds' + A).css('position', 'absolute').css('visibility', 'hidden').appendTo('body'); setTimeout(function () { var a = jQuery('body > .mds' + A); jQuery(aitem).parent().find('#' + A).css('width', (jQuery(a).outerHeight() - 2) + 'px'); jQuery(a).remove() }, 300); isample = jQuery(aitem).parent().find('#' + A).mouseenter(function () { clearTimeout(click_to); click_to = setTimeout(function () { click_flag = true }, 50) }).mouseleave(function () { clearTimeout(click_to); click_to = setTimeout(function () { click_flag = false }, 50) }).focus(function () { jQuery(aitem).focus() }); if (C.color_box) { setTimeout(function () { jQuery(isample).show() }, 150) } init_color(); function init_color() { parsex = jQuery.trim(jQuery(aitem).val() + ''); inputhex = ''; if (parsex == '') { jQuery(isample).val('').css('background', 'url(' + root_path + 'transp.gif) repeat'); jQuery(wrapper).find('input').val('') } else { if (parsex.match(rgb_input)) { rgb_output = true; rgbstring = parsergb(parsex); inputhex = rgb2hex(rgbstring[0], rgbstring[1], rgbstring[2]); } else { for (var i = 0; i < parsex.length; i++) { if (parsex.charAt(i) != '#' && (parsex.charAt(i) + '') in y) { if (inputhex.length < 6) { inputhex += parsex.charAt(i) + '' } } } switch (inputhex.length) { case 0: inputhex = '000000' + inputhex; break; case 1: inputhex = '00000' + inputhex; break; case 2: inputhex = '0000' + inputhex; break; case 3: inputhex = '000' + inputhex; break; case 4: inputhex = '00' + inputhex; break; case 5: inputhex = '0' + inputhex; break } } parsex = hex2rgb(inputhex); parsex = rgb2hsv(parsex['r'], parsex['g'], parsex['b']); hue = 120 - Math.round(parsex['h'] * 1 / 3); if (hue < 0) { hue = 0 } if (hue > 119) { hue = 119 } saturation = parsex['s']; brightness = parsex['v']; jQuery(isample).css('background', '#' + inputhex) } if (C.show_color_on_border) { jQuery(aitem).css('border-color', '#' + inputhex) } }; function action_exit() { if (!opened) { return false } jQuery(slider).remove(); jQuery(sb_sel).remove(); jQuery(switcher).remove(); click_flag = true; switch (C.effect) { case 'zoom': jQuery(wrapper).animate({ width: '0px', height: '0px' }, C.anim_speed, function () { action_ok(); jQuery(wrapper).remove() }); break; case 'slide': jQuery(wrapper).slideUp(C.anim_speed, function () { action_ok(); jQuery(wrapper).remove() }); break; case 'fade': jQuery(wrapper).fadeTo(C.anim_speed, 0, function () { action_ok(); jQuery(wrapper).remove() }); break; default: action_ok(); jQuery(wrapper).remove(); break } opened = false }; function action_ok() { if (userok) { var a = '#' + rgb2hex(jQuery(inp_r).val() * 1, jQuery(inp_g).val() * 1, jQuery(inp_b).val() * 1); var b = jQuery(inp_r).val() * 1 + ',' + jQuery(inp_g).val() * 1 + ',' + jQuery(inp_b).val() * 1; if (jQuery.trim(jQuery(inp_r).val()) == '' && jQuery.trim(jQuery(inp_g).val()) == '' && jQuery.trim(jQuery(inp_b).val()) == '') { jQuery(isample).css('background', 'url(' + root_path + 'transp.gif) repeat'); jQuery(aitem).val('') } else { jQuery(isample).css('background', a); if (C.show_color_on_border) { jQuery(aitem).css('border-color', a) } console.log(rgb_output); if(rgb_output) { jQuery(aitem).val(b); } else { jQuery(aitem).val(a); } } userok = false; C.callback_on_ok() } }; function draw_rgb() { var a = rgb2hsv(jQuery(inp_r).val() * 1, jQuery(inp_g).val() * 1, jQuery(inp_b).val() * 1); hue = -1 * (Math.round(a['h'] * 1 / 3) - 120); if (hue < 0) { hue = 0 } if (hue > 119) { hue = 119 } saturation = a['s']; brightness = a['v']; jQuery(slider).css('left', pos_huebox.left + 'px').css('top', (pos_huebox.top + hue) + 'px'); init_positions(); init_colors(); jQuery(inp_hex).val(rgb2hex(jQuery(inp_r).val() * 1, jQuery(inp_g).val() * 1, jQuery(inp_b).val() * 1)) }; function hex_valid_and_draw() { var a = true, hexistr = ''; hexistr = jQuery.trim(jQuery(inp_hex).val()); switch (hexistr.length) { case 1: hexistr = '00000' + hexistr; break; case 2: hexistr = '0000' + hexistr; break; case 3: hexistr = '000' + hexistr; break; case 4: hexistr = '00' + hexistr; break; case 5: hexistr = '0' + hexistr; break } if (hexistr.length > 0) { for (var i = 0; i < hexistr.length; i++) { if (!((hexistr.charAt(i) + '') in y)) { a = false } } } if (a) { if (hexistr == '') { hue = 119; saturation = 0; brightness = 0 } else { var b = hex2rgb(hexistr); jQuery(inp_r).val(b['r']); jQuery(inp_g).val(b['g']); jQuery(inp_b).val(b['b']); var b = rgb2hsv(b['r'], b['g'], b['b']); hue = -1 * (Math.round(b['h'] * 1 / 3) - 120); if (hue < 0) { hue = 0 } if (hue > 119) { hue = 119 } saturation = b['s']; brightness = b['v'] } jQuery(slider).css('left', pos_huebox.left + 'px').css('top', (pos_huebox.top + hue) + 'px'); init_positions(); init_colors(); if (hexistr == '') { jQuery(colsample).css('background-image', 'url(' + root_path + 'transp.gif)').css('background-repeat', 'repeat'); jQuery(isample).val('').css('background', 'url(' + root_path + 'transp.gif) repeat'); jQuery(switcher).css('background', 'url(' + root_path + 'transp0.gif) -20px 0 no-repeat'); jQuery(wrapper).find('input').val('') } } }; function update_inputs() { var a = hsb2rgb_hex(-1 * (hue - 119) * 3, saturation, brightness, 'rgb'); jQuery(inp_r).val(Math.round(a['r']) * 1); jQuery(inp_g).val(Math.round(a['g']) * 1); jQuery(inp_b).val(Math.round(a['b']) * 1); jQuery(inp_hex).val(rgb2hex(a['r'], a['g'], a['b'])) }; function hsb2rgb_hex(a, b, c, d) { var h = a / 360; var s = b / 100; var v = c / 100; var e = new Array(); var f, var_i, var_1, var_2, var_3, var_r, var_g; if (s == 0) { e['r'] = v * 255; e['g'] = v * 255; e['b'] = v * 255 } else { f = h * 6; var_i = Math.floor(f); var_1 = v * (1 - s); var_2 = v * (1 - s * (f - var_i)); var_3 = v * (1 - s * (1 - (f - var_i))); if (var_i == 0) { var_r = v; var_g = var_3; var_b = var_1 } else if (var_i == 1) { var_r = var_2; var_g = v; var_b = var_1 } else if (var_i == 2) { var_r = var_1; var_g = v; var_b = var_3 } else if (var_i == 3) { var_r = var_1; var_g = var_2; var_b = v } else if (var_i == 4) { var_r = var_3; var_g = var_1; var_b = v } else { var_r = v; var_g = var_1; var_b = var_2 }; e['r'] = Math.round(var_r * 255); e['g'] = Math.round(var_g * 255); e['b'] = Math.round(var_b * 255) } if (d == 'hex') { return rgb2hex(e['r'], e['g'], e['b']) } else if (d == 'rgb') { return (e) } else { return (e) } }; function hex2rgb(h) { var a = new String(); a = h; a.toUpperCase(); h = a; var i, x = '0123456789ABCDEF', c = ''; var b = new Array(); if (h) { h = h.toUpperCase(); for (i = 0; i < 6; i += 2) { switch (i) { case 0: b['r'] = (16 * x.indexOf(h.charAt(i)) + x.indexOf(h.charAt(i + 1))) * 1; break; case 2: b['g'] = (16 * x.indexOf(h.charAt(i)) + x.indexOf(h.charAt(i + 1))) * 1; break; case 4: b['b'] = (16 * x.indexOf(h.charAt(i)) + x.indexOf(h.charAt(i + 1))) * 1; break } } } return b }; function rgb2hsv(a, c, d) { var e = 0, maxrgb = 0, delta = 0, h = 0, s = 0, b = 0; var f = new Array(); h = 0.0; e = Math.min(Math.min(a, c), d); maxrgb = Math.max(Math.max(a, c), d); delta = (maxrgb - e); b = maxrgb; if (maxrgb != 0.0) { s = 255.0 * delta / maxrgb } else { s = 0.0 } if (s != 0.0) { if (a == maxrgb) { h = (c - d) / delta } else { if (c == maxrgb) { h = 2.0 + (d - a) / delta } else { if (d == maxrgb) { h = 4.0 + (a - c) / delta } } } } else { h = -1.0 } h = h * 60; if (h < 0.0) { h = h + 360.0 } f['h'] = Math.round(h); f['s'] = Math.round(s * 100 / 255); f['v'] = Math.round(b * 100 / 255); if (f['h'] > 360) { f['h'] = 360 } if (f['s'] > 100) { f['s'] = 100 } if (f['v'] > 100) { f['v'] = 100 } return f }; function parsergb (string) { array = string.split(','); return array } function rgb2hex(r, g, b) { var a = new Array(); a[0] = r; a[1] = g; a[2] = b; var c = ['0', '1', '2', '3', '4', '5', '6', '7', '8', '9', 'a', 'b', 'c', 'd', 'e', 'f']; var d = ''; for (var i = 0; i < a.length; i++) { dec = parseInt(a[i]); d += c[parseInt(dec / 16)] + c[dec % 16] } return d }; function init_positions() { jQuery(slider).css('left', pos_huebox.left + 'px').css('top', (pos_huebox.top + hue) + 'px'); jQuery(sb_sel).css('left', (pos_sbbox.left + Math.round(saturation * 1.3) - 4) + 'px').css('top', (pos_sbbox.top + jQuery(sbbox).height() - 4 - Math.round(brightness * 1.3)) + 'px') }; function init_colors() { jQuery(sbbox).css('background-color', '#' + hsb2rgb_hex(-1 * (hue - 119) * 3, 100, 100, 'hex')); jQuery(colsample).css('background-color', '#' + hsb2rgb_hex(-1 * (hue - 119) * 3, saturation, brightness, 'hex')).css('background-image', 'none'); jQuery(switcher).css('background', 'url(' + root_path + 'transp0.gif) 0 0 no-repeat') }; setTimeout(function () { aitem_pos = jQuery(aitem).offset() }, 200); function run_excolor_colorpicker() { var b = -1 * C.hue_bar * 20; var c = '<div id="excolor_sample_wrapper"><div id="excolor_sample"></div></div>'; init_color(); jQuery('body').append('<div id="excolor_colorpicker"><div id="excolor_colorpicker_wrapper"><div id="excolor_grad_wrap"><div id="excolor_grad"><div style="width:130px;height:130px;float:left;background-image:url(' + root_path + 'bg.png);background-position:0 0;background-repeat:no-repeat;border:1px solid white;padding:0;margin:0;"></div></div></div><div id="excolor_hue_wrap" style="width:20px;height:130px;float:left;padding:15px 8px 0px 10px;margin:0;border:none;"><div id="excolor_hue" style="width:20px;height:130px;float:left;background:url(' + root_path + 'hue.png) ' + b + 'px 0 no-repeat;margin:0;padding:0;border:none;"></div></div><div id="excolor_data" style="float:left;font-size:10px;font-family: Verdana, Arial, Helvetica, Sans-serif;width:66px;height:140px;margin:0;padding:0;border:none;">' + c + '<div class="excolor_dataitem first"><b class="label">R</b><input id="excolor_r" class="excolor_input excolor_rgb" type="text" size="3" maxlength="3" /></div><div class="excolor_dataitem" style="float:left;padding:3px 0 0 0;margin:0;border:none;"><b class="label">G</b><input id="excolor_g" class="excolor_input excolor_rgb" type="text" size="3" maxlength="3" /></div><div class="excolor_dataitem"><b class="label">B</b><input id="excolor_b" class="excolor_input excolor_rgb" type="text" size="3" maxlength="3" /></div><div class="excolor_dataitem last"><b class="label">#</b><input id="excolor_hex" class="excolor_input" type="text" size="6" maxlength="6" /></div><div style="width:66px;height:15px;padding:0;margin:0;border:none;float:left;"><div id="excolor_ok">OK</div><div id="excolor_close">X</div></div></div></div></div><div id="excolor_picker"></div><div id="excolor_slider"></div><div id="excolor_switcher"></div>'); aitem_pos = jQuery(aitem).offset(); wrapper = jQuery('body > div#excolor_colorpicker').css('left', (aitem_pos.left-150) + 'px').css('top', (aitem_pos.top + jQuery(aitem).outerHeight()) + 'px').mouseenter(function () { clearTimeout(click_to); click_to = setTimeout(function () { click_flag = true }, 50) }).mouseleave(function () { clearTimeout(click_to); click_to = setTimeout(function () { click_flag = false }, 50) }); inp_hex = jQuery(wrapper).find('input#excolor_hex'); switcher = jQuery('body > div#excolor_switcher'); slider = jQuery('body > div#excolor_slider'); sb_sel = jQuery('body > div#excolor_picker'); switch (C.effect) { case 'zoom': jQuery(wrapper).css('width', '0px').css('height', '0px').show().animate({ width: '265px', height: '162px' }, C.anim_speed, function () { jQuery(this).show(); jQuery('body > div#excolor_slider, body > div#excolor_picker').show(); jQuery(switcher).show() }); break; case 'slide': jQuery(wrapper).slideDown(C.anim_speed, function () { jQuery(this).show(); jQuery('body > div#excolor_slider, body > div#excolor_picker').show(); jQuery(switcher).show() }); break; case 'fade': jQuery('body > div#excolor_colorpicker, body > div#excolor_slider, body > div#excolor_picker, body > div#excolor_switcher').fadeTo(1, 0, function () { jQuery(this).show().fadeTo(C.anim_speed, 1) }); break; default: jQuery(wrapper).show(); jQuery(switcher).show(); jQuery('body > div#excolor_slider, body > div#excolor_picker').show(); break } huebox = jQuery(wrapper).find('div#excolor_hue'); sbbox = jQuery(wrapper).find('div#excolor_grad div'); colsample = jQuery(wrapper).find('#excolor_sample'); inp_r = jQuery(wrapper).find('input#excolor_r'); inp_g = jQuery(wrapper).find('input#excolor_g'); inp_b = jQuery(wrapper).find('input#excolor_b'); ok_but = jQuery(wrapper).find('#excolor_ok'); close_but = jQuery(wrapper).find('#excolor_close'); pos_wrap = jQuery(wrapper).offset(); pos_sbbox = jQuery(sbbox).offset(); pos_huebox = jQuery(huebox).offset(); jQuery(switcher).click(function () { if (jQuery.trim(jQuery(inp_r).val()) == '' && jQuery.trim(jQuery(inp_g).val()) == '' && jQuery.trim(jQuery(inp_b).val()) == '') { jQuery(colsample).css('background-image', 'none'); jQuery(this).css('background', 'url(' + root_path + 'transp0.gif) 0 0 no-repeat'); update_inputs() } else { jQuery(colsample).css('background-image', 'url(' + root_path + 'transp.gif)').css('background-repeat', 'repeat'); jQuery(wrapper).find('input').val(''); jQuery(this).css('background', 'url(' + root_path + 'transp0.gif) -20px 0 no-repeat') } }).css('left', (pos_huebox.left - 1) + 'px').css('top', (pos_huebox.top - 15) + 'px').mouseenter(function () { clearTimeout(click_to); click_to = setTimeout(function () { click_flag = true }, 50) }).mouseleave(function () { clearTimeout(click_to); click_to = setTimeout(function () { click_flag = false }, 50) }); jQuery(slider).mouseenter(function () { clearTimeout(click_to); click_to = setTimeout(function () { click_flag = true }, 50) }).mouseleave(function () { clearTimeout(click_to); click_to = setTimeout(function () { click_flag = false }, 50) }); jQuery(sb_sel).mouseenter(function () { clearTimeout(click_to); click_to = setTimeout(function () { click_flag = true }, 50) }).mouseleave(function () { clearTimeout(click_to); click_to = setTimeout(function () { click_flag = false }, 50) }).dblclick(function (e) { jQuery(ok_but).click() }); jQuery(sb_sel).mousedown(function (e) { pos_sel = jQuery(this).offset(); correct_x = e.pageX - pos_sel.left; correct_y = e.pageY - pos_sel.top; j = this; jQuery(switcher).css('background', 'url(' + root_path + 'transp0.gif) 0 0 no-repeat'); e.preventDefault() }).click(function (e) {}); jQuery(slider).mousedown(function (e) { pos_slider = jQuery(this).offset(); correct_x = e.pageX - pos_slider.left; correct_y = e.pageY - pos_slider.top; moved_slider = this; jQuery(switcher).css('background', 'url(' + root_path + 'transp0.gif) 0 0 no-repeat'); e.preventDefault() }); jQuery(huebox).mousedown(function (e) { if (e.pageY >= (pos_huebox.top + 5) && e.pageY <= ((pos_huebox.top + jQuery(huebox).height()) - 6)) { hue = e.pageY - pos_huebox.top - 5; if (hue < 0) hue = 0; if (hue > 119) hue = 119; jQuery(switcher).css('background', 'url(' + root_path + 'transp0.gif) 0 0 no-repeat'); init_positions(); init_colors(); update_inputs(); pos_slider = jQuery(slider).offset(); correct_x = e.pageX - pos_slider.left; correct_y = e.pageY - pos_slider.top; moved_slider = slider; e.preventDefault() } }); jQuery(sbbox).mousedown(function (e) { saturation = Math.round((e.pageX - pos_sbbox.left - 1) / 1.3); if (saturation > 100) { saturation = 100 } if (saturation < 1) { saturation = 1 } brightness = -1 * (Math.round((e.pageY - pos_sbbox.top - 1) / 1.3) - 100); if (brightness > 100) { brightness = 100 } if (brightness < 1) { brightness = 1 } jQuery(switcher).css('background', 'url(' + root_path + 'transp0.gif) 0 0 no-repeat'); init_positions(); jQuery(colsample).css('background-color', '#' + hsb2rgb_hex(-1 * (hue - 119) * 3, saturation, brightness, 'hex')).css('background-image', 'none'); update_inputs(); j = sb_sel; pos_sel = jQuery(j).offset(); correct_x = e.pageX - pos_sel.left; correct_y = e.pageY - pos_sel.top; e.preventDefault() }); jQuery(wrapper).find('input.excolor_input').keypress(function (a) { if (jQuery(this).hasClass('excolor_rgb')) { if (!((String.fromCharCode(a.which) * 1) in w) && !(a.which in z)) { a.preventDefault() } } else { if (!(String.fromCharCode(a.which) in y) && !(a.which in z)) { a.preventDefault() } } }).change(function () { if (jQuery(this).hasClass('excolor_rgb')) { if (jQuery(this).val() == '') { jQuery(this).val('0') } if (isNaN(jQuery(this).val() * 1)) { jQuery(this).val('0') } if (jQuery(this).val() * 1 > 255) { jQuery(this).val('255') } if (jQuery(this).val() * 1 < 0) { jQuery(this).val('0') } draw_rgb() } else { hex_valid_and_draw() } }).keyup(function () { if (jQuery(this).hasClass('excolor_rgb')) { if (jQuery(this).val() == '') { jQuery(this).val('0') } if (isNaN(jQuery(this).val() * 1)) { jQuery(this).val('0') } if (jQuery(this).val() * 1 > 255) { jQuery(this).val('255') } if (jQuery(this).val() * 1 < 0) { jQuery(this).val('0') } draw_rgb() } else { hex_valid_and_draw() } }); inp_hex[0].onpaste = inp_hex[0].oninput = function (e) { clearTimeout(hexto); hexto = setTimeout(function () { hex_valid_and_draw() }, 100) }; inp_r[0].onpaste = inp_r[0].oninput = inp_g[0].onpaste = inp_g[0].oninput = inp_b[0].onpaste = inp_b[0].oninput = function (e) { if (jQuery(this).val() == '') { jQuery(this).val('0') } if (isNaN(jQuery(this).val() * 1)) { jQuery(this).val('0') } if (jQuery(this).val() * 1 > 255) { jQuery(this).val('255') } if (jQuery(this).val() * 1 < 0) { jQuery(this).val('0') } clearTimeout(hexto); hexto = setTimeout(function () { draw_rgb() }, 100) }; jQuery(ok_but).click(function () { userok = true; action_exit() }).mouseenter(function () { jQuery(this).css('background-position', '0 -15px') }).mouseleave(function () { jQuery(this).css('background-position', '0 0') }); jQuery(close_but).click(function () { action_exit() }).mouseenter(function () { jQuery(this).css('background-position', '-47px -15px') }).mouseleave(function () { jQuery(this).css('background-position', '-47px 0') }); init_positions(); jQuery(inp_hex).val(inputhex); hex_valid_and_draw(); opened = true; if (inputhex == '') { jQuery(switcher).css('background', 'url(' + root_path + 'transp0.gif) -20px 0 no-repeat') } else { jQuery(switcher).css('background', 'url(' + root_path + 'transp0.gif) 0 0 no-repeat') } }; jQuery(document).mouseup(function (e) { j = 'mel'; moved_slider = 'mel' }).mousemove(function (e) { if (j != 'mel') { e.preventDefault(); var a = 0, tty = 0; a = e.pageX - correct_x; if (a < (pos_sbbox.left - 4)) { a = pos_sbbox.left - 4 } if (a > (pos_sbbox.left + 125)) { a = pos_sbbox.left + 125 } tty = e.pageY - correct_y; if (tty < (pos_sbbox.top - 4)) { tty = pos_sbbox.top - 4 } if (tty > (pos_sbbox.top + 125)) { tty = pos_sbbox.top + 125 } jQuery(j).css('left', a + 'px').css('top', tty + 'px'); brightness = -1 * (Math.round((tty - pos_sbbox.top + 5) / 1.3) - 100) + 1; saturation = Math.round((a - pos_sbbox.left + 5) / 1.3); if (brightness == 1) { brightness = 0 } if (saturation == 1) { saturation = 0 } jQuery(colsample).css('background-color', '#' + hsb2rgb_hex(-1 * (hue - 119) * 3, saturation, brightness, 'hex')).css('background-image', 'none'); update_inputs() } if (moved_slider != 'mel') { e.preventDefault(); hue = e.pageY - pos_huebox.top - correct_y; if (hue < 0) { hue = 0 } if (hue > 119) { hue = 119 } jQuery(moved_slider).css('left', pos_huebox.left + 'px').css('top', (pos_huebox.top + hue) + 'px'); init_colors(); update_inputs() } }).keydown(function (a) { if (a.keyCode == '27') { a.preventDefault(); action_exit() } if (a.keyCode == '13') { a.preventDefault(); jQuery(ok_but).click() } }).click(function () { if (!click_flag) { action_exit() } }); jQuery(aitem).click(function () { if (!opened) { jQuery('body > div#excolor_slider, body > div#excolor_picker, body > div#excolor_colorpicker').stop().remove(); setTimeout(function () { run_excolor_colorpicker() }, 50) } }).keyup(function () { if (opened) { init_color(); update_inputs(); init_positions(); jQuery(inp_hex).val(inputhex); hex_valid_and_draw() } }); jQuery(isample).click(function () { jQuery(aitem).click() }); if (C.demo_mode) { jQuery(isample).click() } }) };
JavaScript
(function() { var centerContent; $(function() { prettyPrint(); $('input.color-input').excolor({ root_path: 'img/' }); centerContent(); return $(window).resize(centerContent); }); centerContent = function() { var fixed_container_height, half_container_height, half_window_height, new_top, window_height; window_height = $(window).height(); half_window_height = (window_height / 2) - 40; fixed_container_height = $('#container').height(); half_container_height = fixed_container_height / 2; if (half_window_height - half_container_height > 0) { new_top = half_window_height - half_container_height; } else { new_top = 0; } $('#container').css({ height: fixed_container_height, position: 'relative', top: new_top, margin: '0 auto' }); return console.log('New top is (or should be) ' + new_top); }; }).call(this);
JavaScript
jQuery(function($) { $(".cboxElement").colorbox({ width:"730", height:"600", iframe:true }); $("#addimages_avatar").colorbox({ width:"730", height:"600", iframe:true }); $(".btnloadgroup").colorbox({ width:"730", height:"600", iframe:true }); $(".btnloadshow").colorbox({ width:"730", height:"500", iframe:true }); $(".colorbox").colorbox({iframe:true, fixed:true, width:"900", height:"600"}); });
JavaScript
function themanh(){ var path = $("#imgproduct").val(); var ProductID = $("#ProductID").val(); $("#ajaxload").html('<image src="'+url+'templates/images/loading.gif">'); $.post(url+"product/add_img_product",{'path':path,'ProductID':ProductID},function(data) { $("#listimg").html(data); $("#imgproduct").val(''); $("#ajaxload").html(''); }); } function lastorder(){ $("#orderlast").html('<image src="'+url+'templates/images/loading.gif">'); $.post(url+"ajax/orderlast",{},function(data) { $("#orderlast").html(data); }); } function changestatus(value,id){ $("#loadstatus"+id).html('<image src="'+url+'templates/images/loading1.gif">'); $.post(url+"order/changestatus",{'status':value,'id':id},function(data) { $("#loadstatus"+id).html(''); },'json'); } /****** * Tuy chon xem don hang e-com */ function change_list_order(status){ $("#ajax-load").css('display','block'); $.post(url+"order/change_list_order",{'status':status},function(data) { $("#page").html(data.list); $("#pagination_top").html(data.pagination); $("#pagination_bot").html(data.pagination); $("#num_top").html(data.num); $("#num_bot").html(data.num); $("#status").val(data.status); $("#ajax-load").css('display','none'); },'json'); } /******** * Tùy chọn xem don hang nhom mua */ function change_list_order_groupby(status){ $("#ajax-load").css('display','block'); var cartid = $('#CartID').val(); var customer = $("#Pay_FullName").val(); var datebegin = $("#DateBegin").val(); var dateend = $("#DateEnd").val(); var order_name = $("#order_name").val(); var order_value = $("#order_value").val(); $.post(url+"donhang/change_list_order",{'status':status,'cartid':cartid, 'customer':customer,'datebegin':datebegin,'dateend':dateend,'order_value':order_value,'order_name':order_name},function(data) { $("#page").html(data.list); $("#pagination_top").html(data.pagination); $("#pagination_bot").html(data.pagination); $("#num_top").html(data.num); $("#num_bot").html(data.num); $("#status").val(data.status); $("#order_name").val(data.order_name); $("#order_value").val(data.order_value); $("#ajax-load").css('display','none'); },'json'); } /********** * Thong bao chuyen khoan moi nhat */ // Sap xep don hang nhóm mua function order_buy(order_name){ $("#ajax-load").css('display','block'); status = $("#status").val(); order_value = $("#order_value").val(); $.post(url+"donhang/change_list_order",{'status':status,'order_name':order_name,'order_value':order_value,'static':1},function(data) { $("#page").html(data.list); $("#pagination_top").html(data.pagination); $("#pagination_bot").html(data.pagination); $("#num_top").html(data.num); $("#num_bot").html(data.num); $("#status").val(data.status); $("#order_name").val(data.order_name); $("#order_value").val(data.order_value); $("#ajax-load").css('display','none'); },'json'); } // Sap xep don hang e-com function order(order_name){ $("#ajax-load").css('display','block'); status = $("#status").val(); order_value = $("#order_value").val(); $.post(url+"order/change_list_order",{'status':status,'order_name':order_name,'order_value':order_value,'static':1},function(data) { $("#page").html(data.list); $("#pagination_top").html(data.pagination); $("#pagination_bot").html(data.pagination); $("#num_top").html(data.num); $("#num_bot").html(data.num); $("#status").val(data.status); $("#order_name").val(data.order_name); $("#order_value").val(data.order_value); $("#ajax-load").css('display','none'); },'json'); } function transfer_notice_last(){ $("#transfer_notice").html('<image src="'+url+'templates/images/loading.gif">'); $.post(url+"ajax/transfer_notice_last",{},function(data) { $("#transfer_notice").html(data.list); },'json'); } function loadstatic(){ $("#static").html('<image src="'+url+'templates/images/loading.gif">'); $.post(url+"ajax/thongke",{},function(data) { $("#static").html(data); }); } //Site config function loadConfig(){ $("#config").html('<image src="'+url+'templates/images/loading.gif">'); $.post(url+"siteconfig/config",{},function(data) { $("#config").html(data); }); } //Member function updatemember(id){ $("#page").html('<image src="'+url+'templates/images/loading.gif">'); $.post(url+"member/update/",{'id':id},function(data) { $("#page").html(data); }); } //Publish function publish(table,field,id,status){ $("#publish"+id).html('<image src="'+url+'templates/images/loading1.gif">'); $.post(url+"ajax/publish/",{'table':table,'field':field,'id':id,'status':status},function(data) { $("#publish"+id).html(data); }); } //Get Alias function getalias_(){ var name = $('#name').val(); $.post(url+"ajax/getalias/",{'name':name},function(data) { $("#alias").val(data); }); } $(function(){ $("#title").keyup(function() { var word=$(this).val(); $.post(url+"ajax/getalias/",{'name':word},function(data) { $("#alias").val(data); }); return false; }); }); $(function(){ $("#DiscountPercent").keyup(function(){ var discount = $(this).val(); if(discount.length > 2){ alert('Vui lòng nhập phần trăm giảm giá nhỏ hơn 2 chữ số'); } var price = $("#Price").val(); if(price ==''){ alert('Vui lòng nhập giá để tính được số tiền giảm giá'); }else{ var price_new = (discount * price)/100 ; $("#label_discount").html(price_new+' VNĐ') } }); }); function add_rates(){ $("#ratesform").validate({ rules: { ProductsWeight: "required", PriceShip: "required" }, messages: { ProductsWeight: "Vui lòng nhập tổng trọng lượng đơn hàng", PriceShip: "Vui lòng nhập phí vận chuyển" } ,submitHandler: function(form) { var ProductsWeight = $("#ProductsWeight").val(); var PriceShip= $('#PriceShip').val(); var ship_city= $('#ship_city').val(); var ShippingType= $('#ShippingType').val(); var ship_country= $('#ship_country').val(); $("#ajax-load").css('display','block'); $.post(url+"country/add_rates",{'ShippingType':ShippingType,'ProductsWeight':ProductsWeight,'PriceShip':PriceShip,'ship_city':ship_city,'ship_country':ship_country},function(data) { $("#list_rates").html(data.list); $("#ajax-load").css('display','none'); },'json') } }); } function delshipping(id){ $("#ajax-load").css('display','block'); $.post(url+"country/delshipping",{'id':id},function(data) { $('tr#ship'+id).animate({opacity:"hide"}, "slow").remove(); alert('Xóa thành công'); $("#ajax-load").css('display','none'); },'json'); } function show_hide_tag(tag_show){ $("#"+tag_show).toggle(); }
JavaScript
/* * jQuery UI Datepicker 1.8.5 * * Copyright 2010, AUTHORS.txt (http://jqueryui.com/about) * Dual licensed under the MIT or GPL Version 2 licenses. * http://jquery.org/license * * http://docs.jquery.com/UI/Datepicker * * Depends: * jquery.ui.core.js */ (function( $, undefined ) { $.extend($.ui, { datepicker: { version: "1.8.5" } }); var PROP_NAME = 'datepicker'; var dpuuid = new Date().getTime(); /* Date picker manager. Use the singleton instance of this class, $.datepicker, to interact with the date picker. Settings for (groups of) date pickers are maintained in an instance object, allowing multiple different settings on the same page. */ function Datepicker() { this.debug = false; // Change this to true to start debugging this._curInst = null; // The current instance in use this._keyEvent = false; // If the last event was a key event this._disabledInputs = []; // List of date picker inputs that have been disabled this._datepickerShowing = false; // True if the popup picker is showing , false if not this._inDialog = false; // True if showing within a "dialog", false if not this._mainDivId = 'ui-datepicker-div'; // The ID of the main datepicker division this._inlineClass = 'ui-datepicker-inline'; // The name of the inline marker class this._appendClass = 'ui-datepicker-append'; // The name of the append marker class this._triggerClass = 'ui-datepicker-trigger'; // The name of the trigger marker class this._dialogClass = 'ui-datepicker-dialog'; // The name of the dialog marker class this._disableClass = 'ui-datepicker-disabled'; // The name of the disabled covering marker class this._unselectableClass = 'ui-datepicker-unselectable'; // The name of the unselectable cell marker class this._currentClass = 'ui-datepicker-current-day'; // The name of the current day marker class this._dayOverClass = 'ui-datepicker-days-cell-over'; // The name of the day hover marker class this.regional = []; // Available regional settings, indexed by language code this.regional[''] = { // Default regional settings closeText: 'Done', // Display text for close link prevText: '', // Display text for previous month link nextText: '', // Display text for next month link currentText: 'Today', // Display text for current month link monthNames: ['January','February','March','April','May','June', 'July','August','September','October','November','December'], // Names of months for drop-down and formatting monthNamesShort: ['Tháng 1', 'Tháng 2', 'Tháng 3', 'Tháng 4', 'Tháng 5', 'Tháng 6', 'Tháng 7', 'Tháng 8', 'Tháng 9', 'Tháng 10', 'Tháng 11', 'Tháng 12'], // For formatting dayNames: ['CN', 'T2', 'T3', 'T4', 'T5', 'T6', 'T7'], // For formatting dayNamesShort: ['CN', 'T2', 'T3', 'T4', 'T5', 'T6', 'T7'], // For formatting dayNamesMin: ['CN', 'T2', 'T3', 'T4', 'T5', 'T6', 'T7'], // Column headings for days starting at Sunday weekHeader: 'Wk', // Column header for week of the year dateFormat: 'yy/mm/dd', // See format options on parseDate firstDay: 0, // The first day of the week, Sun = 0, Mon = 1, ... isRTL: false, // True if right-to-left language, false if left-to-right showMonthAfterYear: false, // True if the year select precedes month, false for month then year yearSuffix: '' // Additional text to append to the year in the month headers }; this._defaults = { // Global defaults for all the date picker instances showOn: 'focus', // 'focus' for popup on focus, // 'button' for trigger button, or 'both' for either showAnim: 'fadeIn', // Name of jQuery animation for popup showOptions: {}, // Options for enhanced animations defaultDate: null, // Used when field is blank: actual date, // +/-number for offset from today, null for today appendText: '', // Display text following the input box, e.g. showing the format buttonText: '...', // Text for trigger button buttonImage: '', // URL for trigger button image buttonImageOnly: false, // True if the image appears alone, false if it appears on a button hideIfNoPrevNext: false, // True to hide next/previous month links // if not applicable, false to just disable them navigationAsDateFormat: false, // True if date formatting applied to prev/today/next links gotoCurrent: false, // True if today link goes back to current selection instead changeMonth: false, // True if month can be selected directly, false if only prev/next changeYear: false, // True if year can be selected directly, false if only prev/next yearRange: 'c-10:c+10', // Range of years to display in drop-down, // either relative to today's year (-nn:+nn), relative to currently displayed year // (c-nn:c+nn), absolute (nnnn:nnnn), or a combination of the above (nnnn:-n) showOtherMonths: false, // True to show dates in other months, false to leave blank selectOtherMonths: false, // True to allow selection of dates in other months, false for unselectable showWeek: false, // True to show week of the year, false to not show it calculateWeek: this.iso8601Week, // How to calculate the week of the year, // takes a Date and returns the number of the week for it shortYearCutoff: '+10', // Short year values < this are in the current century, // > this are in the previous century, // string value starting with '+' for current year + value minDate: null, // The earliest selectable date, or null for no limit maxDate: null, // The latest selectable date, or null for no limit duration: 'fast', // Duration of display/closure beforeShowDay: null, // Function that takes a date and returns an array with // [0] = true if selectable, false if not, [1] = custom CSS class name(s) or '', // [2] = cell title (optional), e.g. $.datepicker.noWeekends beforeShow: null, // Function that takes an input field and // returns a set of custom settings for the date picker onSelect: null, // Define a callback function when a date is selected onChangeMonthYear: null, // Define a callback function when the month or year is changed onClose: null, // Define a callback function when the datepicker is closed numberOfMonths: 1, // Number of months to show at a time showCurrentAtPos: 0, // The position in multipe months at which to show the current month (starting at 0) stepMonths: 1, // Number of months to step back/forward stepBigMonths: 12, // Number of months to step back/forward for the big links altField: '', // Selector for an alternate field to store selected dates into altFormat: '', // The date format to use for the alternate field constrainInput: true, // The input is constrained by the current date format showButtonPanel: false, // True to show button panel, false to not show it autoSize: false // True to size the input for the date format, false to leave as is }; $.extend(this._defaults, this.regional['']); this.dpDiv = $('<div id="' + this._mainDivId + '" class="ui-datepicker ui-widget ui-widget-content ui-helper-clearfix ui-corner-all ui-helper-hidden-accessible"></div>'); } $.extend(Datepicker.prototype, { /* Class name added to elements to indicate already configured with a date picker. */ markerClassName: 'hasDatepicker', /* Debug logging (if enabled). */ log: function () { if (this.debug) console.log.apply('', arguments); }, // TODO rename to "widget" when switching to widget factory _widgetDatepicker: function() { return this.dpDiv; }, /* Override the default settings for all instances of the date picker. @param settings object - the new settings to use as defaults (anonymous object) @return the manager object */ setDefaults: function(settings) { extendRemove(this._defaults, settings || {}); return this; }, /* Attach the date picker to a jQuery selection. @param target element - the target input field or division or span @param settings object - the new settings to use for this date picker instance (anonymous) */ _attachDatepicker: function(target, settings) { // check for settings on the control itself - in namespace 'date:' var inlineSettings = null; for (var attrName in this._defaults) { var attrValue = target.getAttribute('date:' + attrName); if (attrValue) { inlineSettings = inlineSettings || {}; try { inlineSettings[attrName] = eval(attrValue); } catch (err) { inlineSettings[attrName] = attrValue; } } } var nodeName = target.nodeName.toLowerCase(); var inline = (nodeName == 'div' || nodeName == 'span'); if (!target.id) { this.uuid += 1; target.id = 'dp' + this.uuid; } var inst = this._newInst($(target), inline); inst.settings = $.extend({}, settings || {}, inlineSettings || {}); if (nodeName == 'input') { this._connectDatepicker(target, inst); } else if (inline) { this._inlineDatepicker(target, inst); } }, /* Create a new instance object. */ _newInst: function(target, inline) { var id = target[0].id.replace(/([^A-Za-z0-9_])/g, '\\\\$1'); // escape jQuery meta chars return {id: id, input: target, // associated target selectedDay: 0, selectedMonth: 0, selectedYear: 0, // current selection drawMonth: 0, drawYear: 0, // month being drawn inline: inline, // is datepicker inline or not dpDiv: (!inline ? this.dpDiv : // presentation div $('<div class="' + this._inlineClass + ' ui-datepicker ui-widget ui-widget-content ui-helper-clearfix ui-corner-all"></div>'))}; }, /* Attach the date picker to an input field. */ _connectDatepicker: function(target, inst) { var input = $(target); inst.append = $([]); inst.trigger = $([]); if (input.hasClass(this.markerClassName)) return; this._attachments(input, inst); input.addClass(this.markerClassName).keydown(this._doKeyDown). keypress(this._doKeyPress).keyup(this._doKeyUp). bind("setData.datepicker", function(event, key, value) { inst.settings[key] = value; }).bind("getData.datepicker", function(event, key) { return this._get(inst, key); }); this._autoSize(inst); $.data(target, PROP_NAME, inst); }, /* Make attachments based on settings. */ _attachments: function(input, inst) { var appendText = this._get(inst, 'appendText'); var isRTL = this._get(inst, 'isRTL'); if (inst.append) inst.append.remove(); if (appendText) { inst.append = $('<span class="' + this._appendClass + '">' + appendText + '</span>'); input[isRTL ? 'before' : 'after'](inst.append); } input.unbind('focus', this._showDatepicker); if (inst.trigger) inst.trigger.remove(); var showOn = this._get(inst, 'showOn'); if (showOn == 'focus' || showOn == 'both') // pop-up date picker when in the marked field input.focus(this._showDatepicker); if (showOn == 'button' || showOn == 'both') { // pop-up date picker when button clicked var buttonText = this._get(inst, 'buttonText'); var buttonImage = this._get(inst, 'buttonImage'); inst.trigger = $(this._get(inst, 'buttonImageOnly') ? $('<img/>').addClass(this._triggerClass). attr({ src: buttonImage, alt: buttonText, title: buttonText }) : $('<button type="button"></button>').addClass(this._triggerClass). html(buttonImage == '' ? buttonText : $('<img/>').attr( { src:buttonImage, alt:buttonText, title:buttonText }))); input[isRTL ? 'before' : 'after'](inst.trigger); inst.trigger.click(function() { if ($.datepicker._datepickerShowing && $.datepicker._lastInput == input[0]) $.datepicker._hideDatepicker(); else $.datepicker._showDatepicker(input[0]); return false; }); } }, /* Apply the maximum length for the date format. */ _autoSize: function(inst) { if (this._get(inst, 'autoSize') && !inst.inline) { var date = new Date(2009, 12 - 1, 20); // Ensure double digits var dateFormat = this._get(inst, 'dateFormat'); if (dateFormat.match(/[DM]/)) { var findMax = function(names) { var max = 0; var maxI = 0; for (var i = 0; i < names.length; i++) { if (names[i].length > max) { max = names[i].length; maxI = i; } } return maxI; }; date.setMonth(findMax(this._get(inst, (dateFormat.match(/MM/) ? 'monthNames' : 'monthNamesShort')))); date.setDate(findMax(this._get(inst, (dateFormat.match(/DD/) ? 'dayNames' : 'dayNamesShort'))) + 20 - date.getDay()); } inst.input.attr('size', this._formatDate(inst, date).length); } }, /* Attach an inline date picker to a div. */ _inlineDatepicker: function(target, inst) { var divSpan = $(target); if (divSpan.hasClass(this.markerClassName)) return; divSpan.addClass(this.markerClassName).append(inst.dpDiv). bind("setData.datepicker", function(event, key, value){ inst.settings[key] = value; }).bind("getData.datepicker", function(event, key){ return this._get(inst, key); }); $.data(target, PROP_NAME, inst); this._setDate(inst, this._getDefaultDate(inst), true); this._updateDatepicker(inst); this._updateAlternate(inst); }, /* Pop-up the date picker in a "dialog" box. @param input element - ignored @param date string or Date - the initial date to display @param onSelect function - the function to call when a date is selected @param settings object - update the dialog date picker instance's settings (anonymous object) @param pos int[2] - coordinates for the dialog's position within the screen or event - with x/y coordinates or leave empty for default (screen centre) @return the manager object */ _dialogDatepicker: function(input, date, onSelect, settings, pos) { var inst = this._dialogInst; // internal instance if (!inst) { this.uuid += 1; var id = 'dp' + this.uuid; this._dialogInput = $('<input type="text" id="' + id + '" style="position: absolute; top: -100px; width: 0px; z-index: -10;"/>'); this._dialogInput.keydown(this._doKeyDown); $('body').append(this._dialogInput); inst = this._dialogInst = this._newInst(this._dialogInput, false); inst.settings = {}; $.data(this._dialogInput[0], PROP_NAME, inst); } extendRemove(inst.settings, settings || {}); date = (date && date.constructor == Date ? this._formatDate(inst, date) : date); this._dialogInput.val(date); this._pos = (pos ? (pos.length ? pos : [pos.pageX, pos.pageY]) : null); if (!this._pos) { var browserWidth = document.documentElement.clientWidth; var browserHeight = document.documentElement.clientHeight; var scrollX = document.documentElement.scrollLeft || document.body.scrollLeft; var scrollY = document.documentElement.scrollTop || document.body.scrollTop; this._pos = // should use actual width/height below [(browserWidth / 2) - 100 + scrollX, (browserHeight / 2) - 150 + scrollY]; } // move input on screen for focus, but hidden behind dialog this._dialogInput.css('left', (this._pos[0] + 20) + 'px').css('top', this._pos[1] + 'px'); inst.settings.onSelect = onSelect; this._inDialog = true; this.dpDiv.addClass(this._dialogClass); this._showDatepicker(this._dialogInput[0]); if ($.blockUI) $.blockUI(this.dpDiv); $.data(this._dialogInput[0], PROP_NAME, inst); return this; }, /* Detach a datepicker from its control. @param target element - the target input field or division or span */ _destroyDatepicker: function(target) { var $target = $(target); var inst = $.data(target, PROP_NAME); if (!$target.hasClass(this.markerClassName)) { return; } var nodeName = target.nodeName.toLowerCase(); $.removeData(target, PROP_NAME); if (nodeName == 'input') { inst.append.remove(); inst.trigger.remove(); $target.removeClass(this.markerClassName). unbind('focus', this._showDatepicker). unbind('keydown', this._doKeyDown). unbind('keypress', this._doKeyPress). unbind('keyup', this._doKeyUp); } else if (nodeName == 'div' || nodeName == 'span') $target.removeClass(this.markerClassName).empty(); }, /* Enable the date picker to a jQuery selection. @param target element - the target input field or division or span */ _enableDatepicker: function(target) { var $target = $(target); var inst = $.data(target, PROP_NAME); if (!$target.hasClass(this.markerClassName)) { return; } var nodeName = target.nodeName.toLowerCase(); if (nodeName == 'input') { target.disabled = false; inst.trigger.filter('button'). each(function() { this.disabled = false; }).end(). filter('img').css({opacity: '1.0', cursor: ''}); } else if (nodeName == 'div' || nodeName == 'span') { var inline = $target.children('.' + this._inlineClass); inline.children().removeClass('ui-state-disabled'); } this._disabledInputs = $.map(this._disabledInputs, function(value) { return (value == target ? null : value); }); // delete entry }, /* Disable the date picker to a jQuery selection. @param target element - the target input field or division or span */ _disableDatepicker: function(target) { var $target = $(target); var inst = $.data(target, PROP_NAME); if (!$target.hasClass(this.markerClassName)) { return; } var nodeName = target.nodeName.toLowerCase(); if (nodeName == 'input') { target.disabled = true; inst.trigger.filter('button'). each(function() { this.disabled = true; }).end(). filter('img').css({opacity: '0.5', cursor: 'default'}); } else if (nodeName == 'div' || nodeName == 'span') { var inline = $target.children('.' + this._inlineClass); inline.children().addClass('ui-state-disabled'); } this._disabledInputs = $.map(this._disabledInputs, function(value) { return (value == target ? null : value); }); // delete entry this._disabledInputs[this._disabledInputs.length] = target; }, /* Is the first field in a jQuery collection disabled as a datepicker? @param target element - the target input field or division or span @return boolean - true if disabled, false if enabled */ _isDisabledDatepicker: function(target) { if (!target) { return false; } for (var i = 0; i < this._disabledInputs.length; i++) { if (this._disabledInputs[i] == target) return true; } return false; }, /* Retrieve the instance data for the target control. @param target element - the target input field or division or span @return object - the associated instance data @throws error if a jQuery problem getting data */ _getInst: function(target) { try { return $.data(target, PROP_NAME); } catch (err) { throw 'Missing instance data for this datepicker'; } }, /* Update or retrieve the settings for a date picker attached to an input field or division. @param target element - the target input field or division or span @param name object - the new settings to update or string - the name of the setting to change or retrieve, when retrieving also 'all' for all instance settings or 'defaults' for all global defaults @param value any - the new value for the setting (omit if above is an object or to retrieve a value) */ _optionDatepicker: function(target, name, value) { var inst = this._getInst(target); if (arguments.length == 2 && typeof name == 'string') { return (name == 'defaults' ? $.extend({}, $.datepicker._defaults) : (inst ? (name == 'all' ? $.extend({}, inst.settings) : this._get(inst, name)) : null)); } var settings = name || {}; if (typeof name == 'string') { settings = {}; settings[name] = value; } if (inst) { if (this._curInst == inst) { this._hideDatepicker(); } var date = this._getDateDatepicker(target, true); extendRemove(inst.settings, settings); this._attachments($(target), inst); this._autoSize(inst); this._setDateDatepicker(target, date); this._updateDatepicker(inst); } }, // change method deprecated _changeDatepicker: function(target, name, value) { this._optionDatepicker(target, name, value); }, /* Redraw the date picker attached to an input field or division. @param target element - the target input field or division or span */ _refreshDatepicker: function(target) { var inst = this._getInst(target); if (inst) { this._updateDatepicker(inst); } }, /* Set the dates for a jQuery selection. @param target element - the target input field or division or span @param date Date - the new date */ _setDateDatepicker: function(target, date) { var inst = this._getInst(target); if (inst) { this._setDate(inst, date); this._updateDatepicker(inst); this._updateAlternate(inst); } }, /* Get the date(s) for the first entry in a jQuery selection. @param target element - the target input field or division or span @param noDefault boolean - true if no default date is to be used @return Date - the current date */ _getDateDatepicker: function(target, noDefault) { var inst = this._getInst(target); if (inst && !inst.inline) this._setDateFromField(inst, noDefault); return (inst ? this._getDate(inst) : null); }, /* Handle keystrokes. */ _doKeyDown: function(event) { var inst = $.datepicker._getInst(event.target); var handled = true; var isRTL = inst.dpDiv.is('.ui-datepicker-rtl'); inst._keyEvent = true; if ($.datepicker._datepickerShowing) switch (event.keyCode) { case 9: $.datepicker._hideDatepicker(); handled = false; break; // hide on tab out case 13: var sel = $('td.' + $.datepicker._dayOverClass, inst.dpDiv). add($('td.' + $.datepicker._currentClass, inst.dpDiv)); if (sel[0]) $.datepicker._selectDay(event.target, inst.selectedMonth, inst.selectedYear, sel[0]); else $.datepicker._hideDatepicker(); return false; // don't submit the form break; // select the value on enter case 27: $.datepicker._hideDatepicker(); break; // hide on escape case 33: $.datepicker._adjustDate(event.target, (event.ctrlKey ? -$.datepicker._get(inst, 'stepBigMonths') : -$.datepicker._get(inst, 'stepMonths')), 'M'); break; // previous month/year on page up/+ ctrl case 34: $.datepicker._adjustDate(event.target, (event.ctrlKey ? +$.datepicker._get(inst, 'stepBigMonths') : +$.datepicker._get(inst, 'stepMonths')), 'M'); break; // next month/year on page down/+ ctrl case 35: if (event.ctrlKey || event.metaKey) $.datepicker._clearDate(event.target); handled = event.ctrlKey || event.metaKey; break; // clear on ctrl or command +end case 36: if (event.ctrlKey || event.metaKey) $.datepicker._gotoToday(event.target); handled = event.ctrlKey || event.metaKey; break; // current on ctrl or command +home case 37: if (event.ctrlKey || event.metaKey) $.datepicker._adjustDate(event.target, (isRTL ? +1 : -1), 'D'); handled = event.ctrlKey || event.metaKey; // -1 day on ctrl or command +left if (event.originalEvent.altKey) $.datepicker._adjustDate(event.target, (event.ctrlKey ? -$.datepicker._get(inst, 'stepBigMonths') : -$.datepicker._get(inst, 'stepMonths')), 'M'); // next month/year on alt +left on Mac break; case 38: if (event.ctrlKey || event.metaKey) $.datepicker._adjustDate(event.target, -7, 'D'); handled = event.ctrlKey || event.metaKey; break; // -1 week on ctrl or command +up case 39: if (event.ctrlKey || event.metaKey) $.datepicker._adjustDate(event.target, (isRTL ? -1 : +1), 'D'); handled = event.ctrlKey || event.metaKey; // +1 day on ctrl or command +right if (event.originalEvent.altKey) $.datepicker._adjustDate(event.target, (event.ctrlKey ? +$.datepicker._get(inst, 'stepBigMonths') : +$.datepicker._get(inst, 'stepMonths')), 'M'); // next month/year on alt +right break; case 40: if (event.ctrlKey || event.metaKey) $.datepicker._adjustDate(event.target, +7, 'D'); handled = event.ctrlKey || event.metaKey; break; // +1 week on ctrl or command +down default: handled = false; } else if (event.keyCode == 36 && event.ctrlKey) // display the date picker on ctrl+home $.datepicker._showDatepicker(this); else { handled = false; } if (handled) { event.preventDefault(); event.stopPropagation(); } }, /* Filter entered characters - based on date format. */ _doKeyPress: function(event) { var inst = $.datepicker._getInst(event.target); if ($.datepicker._get(inst, 'constrainInput')) { var chars = $.datepicker._possibleChars($.datepicker._get(inst, 'dateFormat')); var chr = String.fromCharCode(event.charCode == undefined ? event.keyCode : event.charCode); return event.ctrlKey || (chr < ' ' || !chars || chars.indexOf(chr) > -1); } }, /* Synchronise manual entry and field/alternate field. */ _doKeyUp: function(event) { var inst = $.datepicker._getInst(event.target); if (inst.input.val() != inst.lastVal) { try { var date = $.datepicker.parseDate($.datepicker._get(inst, 'dateFormat'), (inst.input ? inst.input.val() : null), $.datepicker._getFormatConfig(inst)); if (date) { // only if valid $.datepicker._setDateFromField(inst); $.datepicker._updateAlternate(inst); $.datepicker._updateDatepicker(inst); } } catch (event) { $.datepicker.log(event); } } return true; }, /* Pop-up the date picker for a given input field. @param input element - the input field attached to the date picker or event - if triggered by focus */ _showDatepicker: function(input) { input = input.target || input; if (input.nodeName.toLowerCase() != 'input') // find from button/image trigger input = $('input', input.parentNode)[0]; if ($.datepicker._isDisabledDatepicker(input) || $.datepicker._lastInput == input) // already here return; var inst = $.datepicker._getInst(input); if ($.datepicker._curInst && $.datepicker._curInst != inst) { $.datepicker._curInst.dpDiv.stop(true, true); } var beforeShow = $.datepicker._get(inst, 'beforeShow'); extendRemove(inst.settings, (beforeShow ? beforeShow.apply(input, [input, inst]) : {})); inst.lastVal = null; $.datepicker._lastInput = input; $.datepicker._setDateFromField(inst); if ($.datepicker._inDialog) // hide cursor input.value = ''; if (!$.datepicker._pos) { // position below input $.datepicker._pos = $.datepicker._findPos(input); $.datepicker._pos[1] += input.offsetHeight; // add the height } var isFixed = false; $(input).parents().each(function() { isFixed |= $(this).css('position') == 'fixed'; return !isFixed; }); if (isFixed && $.browser.opera) { // correction for Opera when fixed and scrolled $.datepicker._pos[0] -= document.documentElement.scrollLeft; $.datepicker._pos[1] -= document.documentElement.scrollTop; } var offset = {left: $.datepicker._pos[0], top: $.datepicker._pos[1]}; $.datepicker._pos = null; // determine sizing offscreen inst.dpDiv.css({position: 'absolute', display: 'block', top: '-1000px'}); $.datepicker._updateDatepicker(inst); // fix width for dynamic number of date pickers // and adjust position before showing offset = $.datepicker._checkOffset(inst, offset, isFixed); inst.dpDiv.css({position: ($.datepicker._inDialog && $.blockUI ? 'static' : (isFixed ? 'fixed' : 'absolute')), display: 'none', left: offset.left + 'px', top: offset.top + 'px'}); if (!inst.inline) { var showAnim = $.datepicker._get(inst, 'showAnim'); var duration = $.datepicker._get(inst, 'duration'); var postProcess = function() { $.datepicker._datepickerShowing = true; var borders = $.datepicker._getBorders(inst.dpDiv); inst.dpDiv.find('iframe.ui-datepicker-cover'). // IE6- only css({left: -borders[0], top: -borders[1], width: inst.dpDiv.outerWidth(), height: inst.dpDiv.outerHeight()}); }; inst.dpDiv.zIndex($(input).zIndex()+1); if ($.effects && $.effects[showAnim]) inst.dpDiv.show(showAnim, $.datepicker._get(inst, 'showOptions'), duration, postProcess); else inst.dpDiv[showAnim || 'show']((showAnim ? duration : null), postProcess); if (!showAnim || !duration) postProcess(); if (inst.input.is(':visible') && !inst.input.is(':disabled')) inst.input.focus(); $.datepicker._curInst = inst; } }, /* Generate the date picker content. */ _updateDatepicker: function(inst) { var self = this; var borders = $.datepicker._getBorders(inst.dpDiv); inst.dpDiv.empty().append(this._generateHTML(inst)) .find('iframe.ui-datepicker-cover') // IE6- only .css({left: -borders[0], top: -borders[1], width: inst.dpDiv.outerWidth(), height: inst.dpDiv.outerHeight()}) .end() .find('button, .ui-datepicker-prev, .ui-datepicker-next, .ui-datepicker-calendar td a') .bind('mouseout', function(){ $(this).removeClass('ui-state-hover'); if(this.className.indexOf('ui-datepicker-prev') != -1) $(this).removeClass('ui-datepicker-prev-hover'); if(this.className.indexOf('ui-datepicker-next') != -1) $(this).removeClass('ui-datepicker-next-hover'); }) .bind('mouseover', function(){ if (!self._isDisabledDatepicker( inst.inline ? inst.dpDiv.parent()[0] : inst.input[0])) { $(this).parents('.ui-datepicker-calendar').find('a').removeClass('ui-state-hover'); $(this).addClass('ui-state-hover'); if(this.className.indexOf('ui-datepicker-prev') != -1) $(this).addClass('ui-datepicker-prev-hover'); if(this.className.indexOf('ui-datepicker-next') != -1) $(this).addClass('ui-datepicker-next-hover'); } }) .end() .find('.' + this._dayOverClass + ' a') .trigger('mouseover') .end(); var numMonths = this._getNumberOfMonths(inst); var cols = numMonths[1]; var width = 17; if (cols > 1) inst.dpDiv.addClass('ui-datepicker-multi-' + cols).css('width', (width * cols) + 'em'); else inst.dpDiv.removeClass('ui-datepicker-multi-2 ui-datepicker-multi-3 ui-datepicker-multi-4').width(''); inst.dpDiv[(numMonths[0] != 1 || numMonths[1] != 1 ? 'add' : 'remove') + 'Class']('ui-datepicker-multi'); inst.dpDiv[(this._get(inst, 'isRTL') ? 'add' : 'remove') + 'Class']('ui-datepicker-rtl'); if (inst == $.datepicker._curInst && $.datepicker._datepickerShowing && inst.input && inst.input.is(':visible') && !inst.input.is(':disabled')) inst.input.focus(); }, /* Retrieve the size of left and top borders for an element. @param elem (jQuery object) the element of interest @return (number[2]) the left and top borders */ _getBorders: function(elem) { var convert = function(value) { return {thin: 1, medium: 2, thick: 3}[value] || value; }; return [parseFloat(convert(elem.css('border-left-width'))), parseFloat(convert(elem.css('border-top-width')))]; }, /* Check positioning to remain on screen. */ _checkOffset: function(inst, offset, isFixed) { var dpWidth = inst.dpDiv.outerWidth(); var dpHeight = inst.dpDiv.outerHeight(); var inputWidth = inst.input ? inst.input.outerWidth() : 0; var inputHeight = inst.input ? inst.input.outerHeight() : 0; var viewWidth = document.documentElement.clientWidth + $(document).scrollLeft(); var viewHeight = document.documentElement.clientHeight + $(document).scrollTop(); offset.left -= (this._get(inst, 'isRTL') ? (dpWidth - inputWidth) : 0); offset.left -= (isFixed && offset.left == inst.input.offset().left) ? $(document).scrollLeft() : 0; offset.top -= (isFixed && offset.top == (inst.input.offset().top + inputHeight)) ? $(document).scrollTop() : 0; // now check if datepicker is showing outside window viewport - move to a better place if so. offset.left -= Math.min(offset.left, (offset.left + dpWidth > viewWidth && viewWidth > dpWidth) ? Math.abs(offset.left + dpWidth - viewWidth) : 0); offset.top -= Math.min(offset.top, (offset.top + dpHeight > viewHeight && viewHeight > dpHeight) ? Math.abs(dpHeight + inputHeight) : 0); return offset; }, /* Find an object's position on the screen. */ _findPos: function(obj) { var inst = this._getInst(obj); var isRTL = this._get(inst, 'isRTL'); while (obj && (obj.type == 'hidden' || obj.nodeType != 1)) { obj = obj[isRTL ? 'previousSibling' : 'nextSibling']; } var position = $(obj).offset(); return [position.left, position.top]; }, /* Hide the date picker from view. @param input element - the input field attached to the date picker */ _hideDatepicker: function(input) { var inst = this._curInst; if (!inst || (input && inst != $.data(input, PROP_NAME))) return; if (this._datepickerShowing) { var showAnim = this._get(inst, 'showAnim'); var duration = this._get(inst, 'duration'); var postProcess = function() { $.datepicker._tidyDialog(inst); this._curInst = null; }; if ($.effects && $.effects[showAnim]) inst.dpDiv.hide(showAnim, $.datepicker._get(inst, 'showOptions'), duration, postProcess); else inst.dpDiv[(showAnim == 'slideDown' ? 'slideUp' : (showAnim == 'fadeIn' ? 'fadeOut' : 'hide'))]((showAnim ? duration : null), postProcess); if (!showAnim) postProcess(); var onClose = this._get(inst, 'onClose'); if (onClose) onClose.apply((inst.input ? inst.input[0] : null), [(inst.input ? inst.input.val() : ''), inst]); // trigger custom callback this._datepickerShowing = false; this._lastInput = null; if (this._inDialog) { this._dialogInput.css({ position: 'absolute', left: '0', top: '-100px' }); if ($.blockUI) { $.unblockUI(); $('body').append(this.dpDiv); } } this._inDialog = false; } }, /* Tidy up after a dialog display. */ _tidyDialog: function(inst) { inst.dpDiv.removeClass(this._dialogClass).unbind('.ui-datepicker-calendar'); }, /* Close date picker if clicked elsewhere. */ _checkExternalClick: function(event) { if (!$.datepicker._curInst) return; var $target = $(event.target); if ($target[0].id != $.datepicker._mainDivId && $target.parents('#' + $.datepicker._mainDivId).length == 0 && !$target.hasClass($.datepicker.markerClassName) && !$target.hasClass($.datepicker._triggerClass) && $.datepicker._datepickerShowing && !($.datepicker._inDialog && $.blockUI)) $.datepicker._hideDatepicker(); }, /* Adjust one of the date sub-fields. */ _adjustDate: function(id, offset, period) { var target = $(id); var inst = this._getInst(target[0]); if (this._isDisabledDatepicker(target[0])) { return; } this._adjustInstDate(inst, offset + (period == 'M' ? this._get(inst, 'showCurrentAtPos') : 0), // undo positioning period); this._updateDatepicker(inst); }, /* Action for current link. */ _gotoToday: function(id) { var target = $(id); var inst = this._getInst(target[0]); if (this._get(inst, 'gotoCurrent') && inst.currentDay) { inst.selectedDay = inst.currentDay; inst.drawMonth = inst.selectedMonth = inst.currentMonth; inst.drawYear = inst.selectedYear = inst.currentYear; } else { var date = new Date(); inst.selectedDay = date.getDate(); inst.drawMonth = inst.selectedMonth = date.getMonth(); inst.drawYear = inst.selectedYear = date.getFullYear(); } this._notifyChange(inst); this._adjustDate(target); }, /* Action for selecting a new month/year. */ _selectMonthYear: function(id, select, period) { var target = $(id); var inst = this._getInst(target[0]); inst._selectingMonthYear = false; inst['selected' + (period == 'M' ? 'Month' : 'Year')] = inst['draw' + (period == 'M' ? 'Month' : 'Year')] = parseInt(select.options[select.selectedIndex].value,10); this._notifyChange(inst); this._adjustDate(target); }, /* Restore input focus after not changing month/year. */ _clickMonthYear: function(id) { var target = $(id); var inst = this._getInst(target[0]); if (inst.input && inst._selectingMonthYear) { setTimeout(function() { inst.input.focus(); }, 0); } inst._selectingMonthYear = !inst._selectingMonthYear; }, /* Action for selecting a day. */ _selectDay: function(id, month, year, td) { var target = $(id); if ($(td).hasClass(this._unselectableClass) || this._isDisabledDatepicker(target[0])) { return; } var inst = this._getInst(target[0]); inst.selectedDay = inst.currentDay = $('a', td).html(); inst.selectedMonth = inst.currentMonth = month; inst.selectedYear = inst.currentYear = year; this._selectDate(id, this._formatDate(inst, inst.currentDay, inst.currentMonth, inst.currentYear)); }, /* Erase the input field and hide the date picker. */ _clearDate: function(id) { var target = $(id); var inst = this._getInst(target[0]); this._selectDate(target, ''); }, /* Update the input field with the selected date. */ _selectDate: function(id, dateStr) { var target = $(id); var inst = this._getInst(target[0]); dateStr = (dateStr != null ? dateStr : this._formatDate(inst)); if (inst.input) inst.input.val(dateStr); this._updateAlternate(inst); var onSelect = this._get(inst, 'onSelect'); if (onSelect) onSelect.apply((inst.input ? inst.input[0] : null), [dateStr, inst]); // trigger custom callback else if (inst.input) inst.input.trigger('change'); // fire the change event if (inst.inline) this._updateDatepicker(inst); else { this._hideDatepicker(); this._lastInput = inst.input[0]; if (typeof(inst.input[0]) != 'object') inst.input.focus(); // restore focus this._lastInput = null; } }, /* Update any alternate field to synchronise with the main field. */ _updateAlternate: function(inst) { var altField = this._get(inst, 'altField'); if (altField) { // update alternate field too var altFormat = this._get(inst, 'altFormat') || this._get(inst, 'dateFormat'); var date = this._getDate(inst); var dateStr = this.formatDate(altFormat, date, this._getFormatConfig(inst)); $(altField).each(function() { $(this).val(dateStr); }); } }, /* Set as beforeShowDay function to prevent selection of weekends. @param date Date - the date to customise @return [boolean, string] - is this date selectable?, what is its CSS class? */ noWeekends: function(date) { var day = date.getDay(); return [(day > 0 && day < 6), '']; }, /* Set as calculateWeek to determine the week of the year based on the ISO 8601 definition. @param date Date - the date to get the week for @return number - the number of the week within the year that contains this date */ iso8601Week: function(date) { var checkDate = new Date(date.getTime()); // Find Thursday of this week starting on Monday checkDate.setDate(checkDate.getDate() + 4 - (checkDate.getDay() || 7)); var time = checkDate.getTime(); checkDate.setMonth(0); // Compare with Jan 1 checkDate.setDate(1); return Math.floor(Math.round((time - checkDate) / 86400000) / 7) + 1; }, /* Parse a string value into a date object. See formatDate below for the possible formats. @param format string - the expected format of the date @param value string - the date in the above format @param settings Object - attributes include: shortYearCutoff number - the cutoff year for determining the century (optional) dayNamesShort string[7] - abbreviated names of the days from Sunday (optional) dayNames string[7] - names of the days from Sunday (optional) monthNamesShort string[12] - abbreviated names of the months (optional) monthNames string[12] - names of the months (optional) @return Date - the extracted date value or null if value is blank */ parseDate: function (format, value, settings) { if (format == null || value == null) throw 'Invalid arguments'; value = (typeof value == 'object' ? value.toString() : value + ''); if (value == '') return null; var shortYearCutoff = (settings ? settings.shortYearCutoff : null) || this._defaults.shortYearCutoff; var dayNamesShort = (settings ? settings.dayNamesShort : null) || this._defaults.dayNamesShort; var dayNames = (settings ? settings.dayNames : null) || this._defaults.dayNames; var monthNamesShort = (settings ? settings.monthNamesShort : null) || this._defaults.monthNamesShort; var monthNames = (settings ? settings.monthNames : null) || this._defaults.monthNames; var year = -1; var month = -1; var day = -1; var doy = -1; var literal = false; // Check whether a format character is doubled var lookAhead = function(match) { var matches = (iFormat + 1 < format.length && format.charAt(iFormat + 1) == match); if (matches) iFormat++; return matches; }; // Extract a number from the string value var getNumber = function(match) { lookAhead(match); var size = (match == '@' ? 14 : (match == '!' ? 20 : (match == 'y' ? 4 : (match == 'o' ? 3 : 2)))); var digits = new RegExp('^\\d{1,' + size + '}'); var num = value.substring(iValue).match(digits); if (!num) throw 'Missing number at position ' + iValue; iValue += num[0].length; return parseInt(num[0], 10); }; // Extract a name from the string value and convert to an index var getName = function(match, shortNames, longNames) { var names = (lookAhead(match) ? longNames : shortNames); for (var i = 0; i < names.length; i++) { if (value.substr(iValue, names[i].length).toLowerCase() == names[i].toLowerCase()) { iValue += names[i].length; return i + 1; } } throw 'Unknown name at position ' + iValue; }; // Confirm that a literal character matches the string value var checkLiteral = function() { if (value.charAt(iValue) != format.charAt(iFormat)) throw 'Unexpected literal at position ' + iValue; iValue++; }; var iValue = 0; for (var iFormat = 0; iFormat < format.length; iFormat++) { if (literal) if (format.charAt(iFormat) == "'" && !lookAhead("'")) literal = false; else checkLiteral(); else switch (format.charAt(iFormat)) { case 'd': day = getNumber('d'); break; case 'D': getName('D', dayNamesShort, dayNames); break; case 'o': doy = getNumber('o'); break; case 'm': month = getNumber('m'); break; case 'M': month = getName('M', monthNamesShort, monthNames); break; case 'y': year = getNumber('y'); break; case '@': var date = new Date(getNumber('@')); year = date.getFullYear(); month = date.getMonth() + 1; day = date.getDate(); break; case '!': var date = new Date((getNumber('!') - this._ticksTo1970) / 10000); year = date.getFullYear(); month = date.getMonth() + 1; day = date.getDate(); break; case "'": if (lookAhead("'")) checkLiteral(); else literal = true; break; default: checkLiteral(); } } if (year == -1) year = new Date().getFullYear(); else if (year < 100) year += new Date().getFullYear() - new Date().getFullYear() % 100 + (year <= shortYearCutoff ? 0 : -100); if (doy > -1) { month = 1; day = doy; do { var dim = this._getDaysInMonth(year, month - 1); if (day <= dim) break; month++; day -= dim; } while (true); } var date = this._daylightSavingAdjust(new Date(year, month - 1, day)); if (date.getFullYear() != year || date.getMonth() + 1 != month || date.getDate() != day) throw 'Invalid date'; // E.g. 31/02/* return date; }, /* Standard date formats. */ ATOM: 'yy-mm-dd', // RFC 3339 (ISO 8601) COOKIE: 'D, dd M yy', ISO_8601: 'yy-mm-dd', RFC_822: 'D, d M y', RFC_850: 'DD, dd-M-y', RFC_1036: 'D, d M y', RFC_1123: 'D, d M yy', RFC_2822: 'D, d M yy', RSS: 'D, d M y', // RFC 822 TICKS: '!', TIMESTAMP: '@', W3C: 'yy-mm-dd', // ISO 8601 _ticksTo1970: (((1970 - 1) * 365 + Math.floor(1970 / 4) - Math.floor(1970 / 100) + Math.floor(1970 / 400)) * 24 * 60 * 60 * 10000000), /* Format a date object into a string value. The format can be combinations of the following: d - day of month (no leading zero) dd - day of month (two digit) o - day of year (no leading zeros) oo - day of year (three digit) D - day name short DD - day name long m - month of year (no leading zero) mm - month of year (two digit) M - month name short MM - month name long y - year (two digit) yy - year (four digit) @ - Unix timestamp (ms since 01/01/1970) ! - Windows ticks (100ns since 01/01/0001) '...' - literal text '' - single quote @param format string - the desired format of the date @param date Date - the date value to format @param settings Object - attributes include: dayNamesShort string[7] - abbreviated names of the days from Sunday (optional) dayNames string[7] - names of the days from Sunday (optional) monthNamesShort string[12] - abbreviated names of the months (optional) monthNames string[12] - names of the months (optional) @return string - the date in the above format */ formatDate: function (format, date, settings) { if (!date) return ''; var dayNamesShort = (settings ? settings.dayNamesShort : null) || this._defaults.dayNamesShort; var dayNames = (settings ? settings.dayNames : null) || this._defaults.dayNames; var monthNamesShort = (settings ? settings.monthNamesShort : null) || this._defaults.monthNamesShort; var monthNames = (settings ? settings.monthNames : null) || this._defaults.monthNames; // Check whether a format character is doubled var lookAhead = function(match) { var matches = (iFormat + 1 < format.length && format.charAt(iFormat + 1) == match); if (matches) iFormat++; return matches; }; // Format a number, with leading zero if necessary var formatNumber = function(match, value, len) { var num = '' + value; if (lookAhead(match)) while (num.length < len) num = '0' + num; return num; }; // Format a name, short or long as requested var formatName = function(match, value, shortNames, longNames) { return (lookAhead(match) ? longNames[value] : shortNames[value]); }; var output = ''; var literal = false; if (date) for (var iFormat = 0; iFormat < format.length; iFormat++) { if (literal) if (format.charAt(iFormat) == "'" && !lookAhead("'")) literal = false; else output += format.charAt(iFormat); else switch (format.charAt(iFormat)) { case 'd': output += formatNumber('d', date.getDate(), 2); break; case 'D': output += formatName('D', date.getDay(), dayNamesShort, dayNames); break; case 'o': output += formatNumber('o', (date.getTime() - new Date(date.getFullYear(), 0, 0).getTime()) / 86400000, 3); break; case 'm': output += formatNumber('m', date.getMonth() + 1, 2); break; case 'M': output += formatName('M', date.getMonth(), monthNamesShort, monthNames); break; case 'y': output += (lookAhead('y') ? date.getFullYear() : (date.getYear() % 100 < 10 ? '0' : '') + date.getYear() % 100); break; case '@': output += date.getTime(); break; case '!': output += date.getTime() * 10000 + this._ticksTo1970; break; case "'": if (lookAhead("'")) output += "'"; else literal = true; break; default: output += format.charAt(iFormat); } } return output; }, /* Extract all possible characters from the date format. */ _possibleChars: function (format) { var chars = ''; var literal = false; // Check whether a format character is doubled var lookAhead = function(match) { var matches = (iFormat + 1 < format.length && format.charAt(iFormat + 1) == match); if (matches) iFormat++; return matches; }; for (var iFormat = 0; iFormat < format.length; iFormat++) if (literal) if (format.charAt(iFormat) == "'" && !lookAhead("'")) literal = false; else chars += format.charAt(iFormat); else switch (format.charAt(iFormat)) { case 'd': case 'm': case 'y': case '@': chars += '0123456789'; break; case 'D': case 'M': return null; // Accept anything case "'": if (lookAhead("'")) chars += "'"; else literal = true; break; default: chars += format.charAt(iFormat); } return chars; }, /* Get a setting value, defaulting if necessary. */ _get: function(inst, name) { return inst.settings[name] !== undefined ? inst.settings[name] : this._defaults[name]; }, /* Parse existing date and initialise date picker. */ _setDateFromField: function(inst, noDefault) { if (inst.input.val() == inst.lastVal) { return; } var dateFormat = this._get(inst, 'dateFormat'); var dates = inst.lastVal = inst.input ? inst.input.val() : null; var date, defaultDate; date = defaultDate = this._getDefaultDate(inst); var settings = this._getFormatConfig(inst); try { date = this.parseDate(dateFormat, dates, settings) || defaultDate; } catch (event) { this.log(event); dates = (noDefault ? '' : dates); } inst.selectedDay = date.getDate(); inst.drawMonth = inst.selectedMonth = date.getMonth(); inst.drawYear = inst.selectedYear = date.getFullYear(); inst.currentDay = (dates ? date.getDate() : 0); inst.currentMonth = (dates ? date.getMonth() : 0); inst.currentYear = (dates ? date.getFullYear() : 0); this._adjustInstDate(inst); }, /* Retrieve the default date shown on opening. */ _getDefaultDate: function(inst) { return this._restrictMinMax(inst, this._determineDate(inst, this._get(inst, 'defaultDate'), new Date())); }, /* A date may be specified as an exact value or a relative one. */ _determineDate: function(inst, date, defaultDate) { var offsetNumeric = function(offset) { var date = new Date(); date.setDate(date.getDate() + offset); return date; }; var offsetString = function(offset) { try { return $.datepicker.parseDate($.datepicker._get(inst, 'dateFormat'), offset, $.datepicker._getFormatConfig(inst)); } catch (e) { // Ignore } var date = (offset.toLowerCase().match(/^c/) ? $.datepicker._getDate(inst) : null) || new Date(); var year = date.getFullYear(); var month = date.getMonth(); var day = date.getDate(); var pattern = /([+-]?[0-9]+)\s*(d|D|w|W|m|M|y|Y)?/g; var matches = pattern.exec(offset); while (matches) { switch (matches[2] || 'd') { case 'd' : case 'D' : day += parseInt(matches[1],10); break; case 'w' : case 'W' : day += parseInt(matches[1],10) * 7; break; case 'm' : case 'M' : month += parseInt(matches[1],10); day = Math.min(day, $.datepicker._getDaysInMonth(year, month)); break; case 'y': case 'Y' : year += parseInt(matches[1],10); day = Math.min(day, $.datepicker._getDaysInMonth(year, month)); break; } matches = pattern.exec(offset); } return new Date(year, month, day); }; date = (date == null ? defaultDate : (typeof date == 'string' ? offsetString(date) : (typeof date == 'number' ? (isNaN(date) ? defaultDate : offsetNumeric(date)) : date))); date = (date && date.toString() == 'Invalid Date' ? defaultDate : date); if (date) { date.setHours(0); date.setMinutes(0); date.setSeconds(0); date.setMilliseconds(0); } return this._daylightSavingAdjust(date); }, /* Handle switch to/from daylight saving. Hours may be non-zero on daylight saving cut-over: > 12 when midnight changeover, but then cannot generate midnight datetime, so jump to 1AM, otherwise reset. @param date (Date) the date to check @return (Date) the corrected date */ _daylightSavingAdjust: function(date) { if (!date) return null; date.setHours(date.getHours() > 12 ? date.getHours() + 2 : 0); return date; }, /* Set the date(s) directly. */ _setDate: function(inst, date, noChange) { var clear = !(date); var origMonth = inst.selectedMonth; var origYear = inst.selectedYear; date = this._restrictMinMax(inst, this._determineDate(inst, date, new Date())); inst.selectedDay = inst.currentDay = date.getDate(); inst.drawMonth = inst.selectedMonth = inst.currentMonth = date.getMonth(); inst.drawYear = inst.selectedYear = inst.currentYear = date.getFullYear(); if ((origMonth != inst.selectedMonth || origYear != inst.selectedYear) && !noChange) this._notifyChange(inst); this._adjustInstDate(inst); if (inst.input) { inst.input.val(clear ? '' : this._formatDate(inst)); } }, /* Retrieve the date(s) directly. */ _getDate: function(inst) { var startDate = (!inst.currentYear || (inst.input && inst.input.val() == '') ? null : this._daylightSavingAdjust(new Date( inst.currentYear, inst.currentMonth, inst.currentDay))); return startDate; }, /* Generate the HTML for the current state of the date picker. */ _generateHTML: function(inst) { var today = new Date(); today = this._daylightSavingAdjust( new Date(today.getFullYear(), today.getMonth(), today.getDate())); // clear time var isRTL = this._get(inst, 'isRTL'); var showButtonPanel = this._get(inst, 'showButtonPanel'); var hideIfNoPrevNext = this._get(inst, 'hideIfNoPrevNext'); var navigationAsDateFormat = this._get(inst, 'navigationAsDateFormat'); var numMonths = this._getNumberOfMonths(inst); var showCurrentAtPos = this._get(inst, 'showCurrentAtPos'); var stepMonths = this._get(inst, 'stepMonths'); var isMultiMonth = (numMonths[0] != 1 || numMonths[1] != 1); var currentDate = this._daylightSavingAdjust((!inst.currentDay ? new Date(9999, 9, 9) : new Date(inst.currentYear, inst.currentMonth, inst.currentDay))); var minDate = this._getMinMaxDate(inst, 'min'); var maxDate = this._getMinMaxDate(inst, 'max'); var drawMonth = inst.drawMonth - showCurrentAtPos; var drawYear = inst.drawYear; if (drawMonth < 0) { drawMonth += 12; drawYear--; } if (maxDate) { var maxDraw = this._daylightSavingAdjust(new Date(maxDate.getFullYear(), maxDate.getMonth() - (numMonths[0] * numMonths[1]) + 1, maxDate.getDate())); maxDraw = (minDate && maxDraw < minDate ? minDate : maxDraw); while (this._daylightSavingAdjust(new Date(drawYear, drawMonth, 1)) > maxDraw) { drawMonth--; if (drawMonth < 0) { drawMonth = 11; drawYear--; } } } inst.drawMonth = drawMonth; inst.drawYear = drawYear; var prevText = this._get(inst, 'prevText'); prevText = (!navigationAsDateFormat ? prevText : this.formatDate(prevText, this._daylightSavingAdjust(new Date(drawYear, drawMonth - stepMonths, 1)), this._getFormatConfig(inst))); var prev = (this._canAdjustMonth(inst, -1, drawYear, drawMonth) ? '<a class="ui-datepicker-prev ui-corner-all" onclick="DP_jQuery_' + dpuuid + '.datepicker._adjustDate(\'#' + inst.id + '\', -' + stepMonths + ', \'M\');"' + ' title="' + prevText + '"><span class="ui-icon ui-icon-circle-triangle-' + ( isRTL ? 'e' : 'w') + '"></span></a>' : (hideIfNoPrevNext ? '' : '<a class="ui-datepicker-prev ui-corner-all ui-state-disabled" title="'+ prevText +'"><span class="ui-icon ui-icon-circle-triangle-' + ( isRTL ? 'e' : 'w') + '">' + prevText + '</span></a>')); var nextText = this._get(inst, 'nextText'); nextText = (!navigationAsDateFormat ? nextText : this.formatDate(nextText, this._daylightSavingAdjust(new Date(drawYear, drawMonth + stepMonths, 1)), this._getFormatConfig(inst))); var next = (this._canAdjustMonth(inst, +1, drawYear, drawMonth) ? '<a class="ui-datepicker-next ui-corner-all" onclick="DP_jQuery_' + dpuuid + '.datepicker._adjustDate(\'#' + inst.id + '\', +' + stepMonths + ', \'M\');"' + ' title="' + nextText + '"><span class="ui-icon ui-icon-circle-triangle-' + ( isRTL ? 'w' : 'e') + '"></span></a>' : (hideIfNoPrevNext ? '' : '<a class="ui-datepicker-next ui-corner-all ui-state-disabled" title="'+ nextText + '"><span class="ui-icon ui-icon-circle-triangle-' + ( isRTL ? 'w' : 'e') + '">' + nextText + '</span></a>')); var currentText = this._get(inst, 'currentText'); var gotoDate = (this._get(inst, 'gotoCurrent') && inst.currentDay ? currentDate : today); currentText = (!navigationAsDateFormat ? currentText : this.formatDate(currentText, gotoDate, this._getFormatConfig(inst))); var controls = (!inst.inline ? '<button type="button" class="ui-datepicker-close ui-state-default ui-priority-primary ui-corner-all" onclick="DP_jQuery_' + dpuuid + '.datepicker._hideDatepicker();">' + this._get(inst, 'closeText') + '</button>' : ''); var buttonPanel = (showButtonPanel) ? '<div class="ui-datepicker-buttonpane ui-widget-content">' + (isRTL ? controls : '') + (this._isInRange(inst, gotoDate) ? '<button type="button" class="ui-datepicker-current ui-state-default ui-priority-secondary ui-corner-all" onclick="DP_jQuery_' + dpuuid + '.datepicker._gotoToday(\'#' + inst.id + '\');"' + '>' + currentText + '</button>' : '') + (isRTL ? '' : controls) + '</div>' : ''; var firstDay = parseInt(this._get(inst, 'firstDay'),10); firstDay = (isNaN(firstDay) ? 0 : firstDay); var showWeek = this._get(inst, 'showWeek'); var dayNames = this._get(inst, 'dayNames'); var dayNamesShort = this._get(inst, 'dayNamesShort'); var dayNamesMin = this._get(inst, 'dayNamesMin'); var monthNames = this._get(inst, 'monthNames'); var monthNamesShort = this._get(inst, 'monthNamesShort'); var beforeShowDay = this._get(inst, 'beforeShowDay'); var showOtherMonths = this._get(inst, 'showOtherMonths'); var selectOtherMonths = this._get(inst, 'selectOtherMonths'); var calculateWeek = this._get(inst, 'calculateWeek') || this.iso8601Week; var defaultDate = this._getDefaultDate(inst); var html = ''; for (var row = 0; row < numMonths[0]; row++) { var group = ''; for (var col = 0; col < numMonths[1]; col++) { var selectedDate = this._daylightSavingAdjust(new Date(drawYear, drawMonth, inst.selectedDay)); var cornerClass = ' ui-corner-all'; var calender = ''; if (isMultiMonth) { calender += '<div class="ui-datepicker-group'; if (numMonths[1] > 1) switch (col) { case 0: calender += ' ui-datepicker-group-first'; cornerClass = ' ui-corner-' + (isRTL ? 'right' : 'left'); break; case numMonths[1]-1: calender += ' ui-datepicker-group-last'; cornerClass = ' ui-corner-' + (isRTL ? 'left' : 'right'); break; default: calender += ' ui-datepicker-group-middle'; cornerClass = ''; break; } calender += '">'; } calender += '<div class="ui-datepicker-header ui-widget-header ui-helper-clearfix' + cornerClass + '">' + (/all|left/.test(cornerClass) && row == 0 ? (isRTL ? next : prev) : '') + (/all|right/.test(cornerClass) && row == 0 ? (isRTL ? prev : next) : '') + this._generateMonthYearHeader(inst, drawMonth, drawYear, minDate, maxDate, row > 0 || col > 0, monthNames, monthNamesShort) + // draw month headers '</div><table class="ui-datepicker-calendar"><thead>' + '<tr>'; var thead = (showWeek ? '<th class="ui-datepicker-week-col">' + this._get(inst, 'weekHeader') + '</th>' : ''); for (var dow = 0; dow < 7; dow++) { // days of the week var day = (dow + firstDay) % 7; thead += '<th' + ((dow + firstDay + 6) % 7 >= 5 ? ' class="ui-datepicker-week-end"' : '') + '>' + '<span title="' + dayNames[day] + '">' + dayNamesMin[day] + '</span></th>'; } calender += thead + '</tr></thead><tbody>'; var daysInMonth = this._getDaysInMonth(drawYear, drawMonth); if (drawYear == inst.selectedYear && drawMonth == inst.selectedMonth) inst.selectedDay = Math.min(inst.selectedDay, daysInMonth); var leadDays = (this._getFirstDayOfMonth(drawYear, drawMonth) - firstDay + 7) % 7; var numRows = (isMultiMonth ? 6 : Math.ceil((leadDays + daysInMonth) / 7)); // calculate the number of rows to generate var printDate = this._daylightSavingAdjust(new Date(drawYear, drawMonth, 1 - leadDays)); for (var dRow = 0; dRow < numRows; dRow++) { // create date picker rows calender += '<tr>'; var tbody = (!showWeek ? '' : '<td class="ui-datepicker-week-col">' + this._get(inst, 'calculateWeek')(printDate) + '</td>'); for (var dow = 0; dow < 7; dow++) { // create date picker days var daySettings = (beforeShowDay ? beforeShowDay.apply((inst.input ? inst.input[0] : null), [printDate]) : [true, '']); var otherMonth = (printDate.getMonth() != drawMonth); var unselectable = (otherMonth && !selectOtherMonths) || !daySettings[0] || (minDate && printDate < minDate) || (maxDate && printDate > maxDate); tbody += '<td class="' + ((dow + firstDay + 6) % 7 >= 5 ? ' ui-datepicker-week-end' : '') + // highlight weekends (otherMonth ? ' ui-datepicker-other-month' : '') + // highlight days from other months ((printDate.getTime() == selectedDate.getTime() && drawMonth == inst.selectedMonth && inst._keyEvent) || // user pressed key (defaultDate.getTime() == printDate.getTime() && defaultDate.getTime() == selectedDate.getTime()) ? // or defaultDate is current printedDate and defaultDate is selectedDate ' ' + this._dayOverClass : '') + // highlight selected day (unselectable ? ' ' + this._unselectableClass + ' ui-state-disabled': '') + // highlight unselectable days (otherMonth && !showOtherMonths ? '' : ' ' + daySettings[1] + // highlight custom dates (printDate.getTime() == currentDate.getTime() ? ' ' + this._currentClass : '') + // highlight selected day (printDate.getTime() == today.getTime() ? ' ui-datepicker-today' : '')) + '"' + // highlight today (if different) ((!otherMonth || showOtherMonths) && daySettings[2] ? ' title="' + daySettings[2] + '"' : '') + // cell title (unselectable ? '' : ' onclick="DP_jQuery_' + dpuuid + '.datepicker._selectDay(\'#' + inst.id + '\',' + printDate.getMonth() + ',' + printDate.getFullYear() + ', this);return false;"') + '>' + // actions (otherMonth && !showOtherMonths ? '&#xa0;' : // display for other months (unselectable ? '<span class="ui-state-default">' + printDate.getDate() + '</span>' : '<a class="ui-state-default' + (printDate.getTime() == today.getTime() ? ' ui-state-highlight' : '') + (printDate.getTime() == selectedDate.getTime() ? ' ui-state-active' : '') + // highlight selected day (otherMonth ? ' ui-priority-secondary' : '') + // distinguish dates from other months '" href="#">' + printDate.getDate() + '</a>')) + '</td>'; // display selectable date printDate.setDate(printDate.getDate() + 1); printDate = this._daylightSavingAdjust(printDate); } calender += tbody + '</tr>'; } drawMonth++; if (drawMonth > 11) { drawMonth = 0; drawYear++; } calender += '</tbody></table>' + (isMultiMonth ? '</div>' + ((numMonths[0] > 0 && col == numMonths[1]-1) ? '<div class="ui-datepicker-row-break"></div>' : '') : ''); group += calender; } html += group; } html += buttonPanel + ($.browser.msie && parseInt($.browser.version,10) < 7 && !inst.inline ? '<iframe src="javascript:false;" class="ui-datepicker-cover" frameborder="0"></iframe>' : ''); inst._keyEvent = false; return html; }, /* Generate the month and year header. */ _generateMonthYearHeader: function(inst, drawMonth, drawYear, minDate, maxDate, secondary, monthNames, monthNamesShort) { var changeMonth = this._get(inst, 'changeMonth'); var changeYear = this._get(inst, 'changeYear'); var showMonthAfterYear = this._get(inst, 'showMonthAfterYear'); var html = '<div class="ui-datepicker-title">'; var monthHtml = ''; // month selection if (secondary || !changeMonth) monthHtml += '<span class="ui-datepicker-month">' + monthNames[drawMonth] + '</span>'; else { var inMinYear = (minDate && minDate.getFullYear() == drawYear); var inMaxYear = (maxDate && maxDate.getFullYear() == drawYear); monthHtml += '<select class="ui-datepicker-month" ' + 'onchange="DP_jQuery_' + dpuuid + '.datepicker._selectMonthYear(\'#' + inst.id + '\', this, \'M\');" ' + 'onclick="DP_jQuery_' + dpuuid + '.datepicker._clickMonthYear(\'#' + inst.id + '\');"' + '>'; for (var month = 0; month < 12; month++) { if ((!inMinYear || month >= minDate.getMonth()) && (!inMaxYear || month <= maxDate.getMonth())) monthHtml += '<option value="' + month + '"' + (month == drawMonth ? ' selected="selected"' : '') + '>' + monthNamesShort[month] + '</option>'; } monthHtml += '</select>'; } if (!showMonthAfterYear) html += monthHtml + (secondary || !(changeMonth && changeYear) ? '&#xa0;' : ''); // year selection if (secondary || !changeYear) html += '<span class="ui-datepicker-year">' + drawYear + '</span>'; else { // determine range of years to display var years = this._get(inst, 'yearRange').split(':'); var thisYear = new Date().getFullYear(); var determineYear = function(value) { var year = (value.match(/c[+-].*/) ? drawYear + parseInt(value.substring(1), 10) : (value.match(/[+-].*/) ? thisYear + parseInt(value, 10) : parseInt(value, 10))); return (isNaN(year) ? thisYear : year); }; var year = determineYear(years[0]); var endYear = Math.max(year, determineYear(years[1] || '')); year = (minDate ? Math.max(year, minDate.getFullYear()) : year); endYear = (maxDate ? Math.min(endYear, maxDate.getFullYear()) : endYear); html += '<select class="ui-datepicker-year" ' + 'onchange="DP_jQuery_' + dpuuid + '.datepicker._selectMonthYear(\'#' + inst.id + '\', this, \'Y\');" ' + 'onclick="DP_jQuery_' + dpuuid + '.datepicker._clickMonthYear(\'#' + inst.id + '\');"' + '>'; for (; year <= endYear; year++) { html += '<option value="' + year + '"' + (year == drawYear ? ' selected="selected"' : '') + '>' + year + '</option>'; } html += '</select>'; } html += this._get(inst, 'yearSuffix'); if (showMonthAfterYear) html += (secondary || !(changeMonth && changeYear) ? '&#xa0;' : '') + monthHtml; html += '</div>'; // Close datepicker_header return html; }, /* Adjust one of the date sub-fields. */ _adjustInstDate: function(inst, offset, period) { var year = inst.drawYear + (period == 'Y' ? offset : 0); var month = inst.drawMonth + (period == 'M' ? offset : 0); var day = Math.min(inst.selectedDay, this._getDaysInMonth(year, month)) + (period == 'D' ? offset : 0); var date = this._restrictMinMax(inst, this._daylightSavingAdjust(new Date(year, month, day))); inst.selectedDay = date.getDate(); inst.drawMonth = inst.selectedMonth = date.getMonth(); inst.drawYear = inst.selectedYear = date.getFullYear(); if (period == 'M' || period == 'Y') this._notifyChange(inst); }, /* Ensure a date is within any min/max bounds. */ _restrictMinMax: function(inst, date) { var minDate = this._getMinMaxDate(inst, 'min'); var maxDate = this._getMinMaxDate(inst, 'max'); date = (minDate && date < minDate ? minDate : date); date = (maxDate && date > maxDate ? maxDate : date); return date; }, /* Notify change of month/year. */ _notifyChange: function(inst) { var onChange = this._get(inst, 'onChangeMonthYear'); if (onChange) onChange.apply((inst.input ? inst.input[0] : null), [inst.selectedYear, inst.selectedMonth + 1, inst]); }, /* Determine the number of months to show. */ _getNumberOfMonths: function(inst) { var numMonths = this._get(inst, 'numberOfMonths'); return (numMonths == null ? [1, 1] : (typeof numMonths == 'number' ? [1, numMonths] : numMonths)); }, /* Determine the current maximum date - ensure no time components are set. */ _getMinMaxDate: function(inst, minMax) { return this._determineDate(inst, this._get(inst, minMax + 'Date'), null); }, /* Find the number of days in a given month. */ _getDaysInMonth: function(year, month) { return 32 - new Date(year, month, 32).getDate(); }, /* Find the day of the week of the first of a month. */ _getFirstDayOfMonth: function(year, month) { return new Date(year, month, 1).getDay(); }, /* Determines if we should allow a "next/prev" month display change. */ _canAdjustMonth: function(inst, offset, curYear, curMonth) { var numMonths = this._getNumberOfMonths(inst); var date = this._daylightSavingAdjust(new Date(curYear, curMonth + (offset < 0 ? offset : numMonths[0] * numMonths[1]), 1)); if (offset < 0) date.setDate(this._getDaysInMonth(date.getFullYear(), date.getMonth())); return this._isInRange(inst, date); }, /* Is the given date in the accepted range? */ _isInRange: function(inst, date) { var minDate = this._getMinMaxDate(inst, 'min'); var maxDate = this._getMinMaxDate(inst, 'max'); return ((!minDate || date.getTime() >= minDate.getTime()) && (!maxDate || date.getTime() <= maxDate.getTime())); }, /* Provide the configuration settings for formatting/parsing. */ _getFormatConfig: function(inst) { var shortYearCutoff = this._get(inst, 'shortYearCutoff'); shortYearCutoff = (typeof shortYearCutoff != 'string' ? shortYearCutoff : new Date().getFullYear() % 100 + parseInt(shortYearCutoff, 10)); return {shortYearCutoff: shortYearCutoff, dayNamesShort: this._get(inst, 'dayNamesShort'), dayNames: this._get(inst, 'dayNames'), monthNamesShort: this._get(inst, 'monthNamesShort'), monthNames: this._get(inst, 'monthNames')}; }, /* Format the given date for display. */ _formatDate: function(inst, day, month, year) { if (!day) { inst.currentDay = inst.selectedDay; inst.currentMonth = inst.selectedMonth; inst.currentYear = inst.selectedYear; } var date = (day ? (typeof day == 'object' ? day : this._daylightSavingAdjust(new Date(year, month, day))) : this._daylightSavingAdjust(new Date(inst.currentYear, inst.currentMonth, inst.currentDay))); return this.formatDate(this._get(inst, 'dateFormat'), date, this._getFormatConfig(inst)); } }); /* jQuery extend now ignores nulls! */ function extendRemove(target, props) { $.extend(target, props); for (var name in props) if (props[name] == null || props[name] == undefined) target[name] = props[name]; return target; }; /* Determine whether an object is an array. */ function isArray(a) { return (a && (($.browser.safari && typeof a == 'object' && a.length) || (a.constructor && a.constructor.toString().match(/\Array\(\)/)))); }; /* Invoke the datepicker functionality. @param options string - a command, optionally followed by additional parameters or Object - settings for attaching new datepicker functionality @return jQuery object */ $.fn.datepicker = function(options){ /* Initialise the date picker. */ if (!$.datepicker.initialized) { $(document).mousedown($.datepicker._checkExternalClick). find('body').append($.datepicker.dpDiv); $.datepicker.initialized = true; } var otherArgs = Array.prototype.slice.call(arguments, 1); if (typeof options == 'string' && (options == 'isDisabled' || options == 'getDate' || options == 'widget')) return $.datepicker['_' + options + 'Datepicker']. apply($.datepicker, [this[0]].concat(otherArgs)); if (options == 'option' && arguments.length == 2 && typeof arguments[1] == 'string') return $.datepicker['_' + options + 'Datepicker']. apply($.datepicker, [this[0]].concat(otherArgs)); return this.each(function() { typeof options == 'string' ? $.datepicker['_' + options + 'Datepicker']. apply($.datepicker, [this].concat(otherArgs)) : $.datepicker._attachDatepicker(this, options); }); }; $.datepicker = new Datepicker(); // singleton instance $.datepicker.initialized = false; $.datepicker.uuid = new Date().getTime(); $.datepicker.version = "1.8.5"; // Workaround for #4055 // Add another global to avoid noConflict issues with inline event handlers window['DP_jQuery_' + dpuuid] = $; })(jQuery);
JavaScript
//Javasript name: My Date Time Picker //Date created: 16-Nov-2003 23:19 //Creator: TengYong Ng //Website: http://www.rainforestnet.com //Copyright (c) 2003 TengYong Ng //FileName: DateTimePicker_css.js //Version: 2.2.0 // Note: Permission given to use and modify this script in ANY kind of applications if // header lines are left unchanged. //Permission is granted to redistribute and modify this javascript under the terms of the GNU General Public License 3.0. //New Css style version added by Yvan Lavoie (Québec, Canada) 29-Jan-2009 //Formatted for JSLint compatibility by Labsmedia.com (30-Dec-2010) //Global variables var winCal; var dtToday; var Cal; var MonthName; var WeekDayName1; var WeekDayName2; var exDateTime;//Existing Date and Time var selDate;//selected date. version 1.7 var calSpanID = "calBorder"; // span ID var domStyle = null; // span DOM object with style var cnLeft = "0";//left coordinate of calendar span var cnTop = "0";//top coordinate of calendar span var xpos = 0; // mouse x position var ypos = 0; // mouse y position var calHeight = 0; // calendar height var CalWidth = 208;// calendar width var CellWidth = 30;// width of day cell. var TimeMode = 24;// TimeMode value. 12 or 24 var StartYear = 1940; //First Year in drop down year selection var EndYear = 5; // The last year of pickable date. if current year is 2011, the last year that still picker will be 2016 (2011+5) var CalPosOffsetX = -10; //X position offset relative to calendar icon, can be negative value var CalPosOffsetY = 40; //Y position offset relative to calendar icon, can be negative value //Configurable parameters //var WindowTitle = "DateTime Picker";//Date Time Picker title. var SpanBorderColor = "#E5E5E5";//span border color var SpanBgColor = "#FFFFFF"; //span background color var MonthYearColor = "#cc0033"; //Font Color of Month and Year in Calendar header. var WeekHeadColor = "#18861B"; //var WeekHeadColor="#18861B";//Background Color in Week header. var SundayColor = "#C0F64F"; //var SundayColor="#C0F64F";//Background color of Sunday. var SaturdayColor = "#C0F64F"; //Background color of Saturday. var WeekDayColor = "#FFEDA6"; //Background color of weekdays. var FontColor = "blue"; //color of font in Calendar day cell. var TodayColor = "#ffbd35"; //var TodayColor="#FFFF33";//Background color of today. var SelDateColor = "#8DD53C"; //var SelDateColor = "#8DD53C";//Backgrond color of selected date in textbox. var YrSelColor = "#cc0033"; //color of font of Year selector. var MthSelColor = "#cc0033"; //color of font of Month selector if "MonthSelector" is "arrow". var HoverColor = "#E0FF38"; //color when mouse move over. var DisableColor = "#999966"; //color of disabled cell. var CalBgColor = "#ffffff"; //Background color of Calendar window. var WeekChar = 2;//number of character for week day. if 2 then Mo,Tu,We. if 3 then Mon,Tue,Wed. var DateSeparator = "-";//Date Separator, you can change it to "-" if you want. var ShowLongMonth = true;//Show long month name in Calendar header. example: "January". var ShowMonthYear = true;//Show Month and Year in Calendar header. var ThemeBg = "";//Background image of Calendar window. var PrecedeZero = true;//Preceding zero [true|false] var MondayFirstDay = true;//true:Use Monday as first day; false:Sunday as first day. [true|false] //added in version 1.7 var UseImageFiles = true;//Use image files with "arrows" and "close" button var DisableBeforeToday = false; //Make date before today unclickable. var imageFilesPath = url + "templates/images/date_picker/"; //use the Month and Weekday in your preferred language. var MonthName = ["Tháng 1", "Tháng 2", "Tháng 3", "Tháng 4", "Tháng 5", "Tháng 6", "Tháng 7", "Tháng 8", "Tháng 9", "Tháng 10", "Tháng 11", "Tháng 12"]; var WeekDayName1 = ["Sunday", "Monday", "Tuesday", "Wednesday", "Thursday", "Friday", "Saturday"]; var WeekDayName2 = ["T2", "T3", "T4", "T5", "T6", "T7", "CN"]; //end Configurable parameters //end Global variable // Calendar prototype function Calendar(pDate, pCtrl) { //Properties this.Date = pDate.getDate();//selected date this.Month = pDate.getMonth();//selected month number this.Year = pDate.getFullYear();//selected year in 4 digits this.Hours = pDate.getHours(); if (pDate.getMinutes() < 10) { this.Minutes = "0" + pDate.getMinutes(); } else { this.Minutes = pDate.getMinutes(); } if (pDate.getSeconds() < 10) { this.Seconds = "0" + pDate.getSeconds(); } else { this.Seconds = pDate.getSeconds(); } this.MyWindow = winCal; this.Ctrl = pCtrl; this.Format = "ddMMyyyy"; this.Separator = DateSeparator; this.ShowTime = false; this.Scroller = "DROPDOWN"; if (pDate.getHours() < 12) { this.AMorPM = "AM"; } else { this.AMorPM = "PM"; } this.ShowSeconds = false; } Calendar.prototype.GetMonthIndex = function (shortMonthName) { for (var i = 0; i < 12; i += 1) { if (MonthName[i].substring(0, 3).toUpperCase() === shortMonthName.toUpperCase()) { return i; } } }; Calendar.prototype.IncYear = function () { if (Cal.Year <= dtToday.getFullYear()+EndYear) Cal.Year += 1; }; Calendar.prototype.DecYear = function () { if (Cal.Year > StartYear) Cal.Year -= 1; }; Calendar.prototype.IncMonth = function() { if (Cal.Year <= dtToday.getFullYear() + EndYear) { Cal.Month += 1; if (Cal.Month >= 12) { Cal.Month = 0; Cal.IncYear(); } } }; Calendar.prototype.DecMonth = function() { if (Cal.Year >= StartYear) { Cal.Month -= 1; if (Cal.Month < 0) { Cal.Month = 11; Cal.DecYear(); } } }; Calendar.prototype.SwitchMth = function (intMth) { Cal.Month = parseInt(intMth, 10); }; Calendar.prototype.SwitchYear = function (intYear) { Cal.Year = parseInt(intYear, 10); }; Calendar.prototype.SetHour = function (intHour) { var MaxHour, MinHour, HourExp = new RegExp("^\\d\\d"), SingleDigit = new RegExp("\\d"); if (TimeMode === 24) { MaxHour = 23; MinHour = 0; } else if (TimeMode === 12) { MaxHour = 12; MinHour = 1; } else { alert("TimeMode can only be 12 or 24"); } if ((HourExp.test(intHour) || SingleDigit.test(intHour)) && (parseInt(intHour, 10) > MaxHour)) { intHour = MinHour; } else if ((HourExp.test(intHour) || SingleDigit.test(intHour)) && (parseInt(intHour, 10) < MinHour)) { intHour = MaxHour; } if (SingleDigit.test(intHour)) { intHour = "0" + intHour; } if (HourExp.test(intHour) && (parseInt(intHour, 10) <= MaxHour) && (parseInt(intHour, 10) >= MinHour)) { if ((TimeMode === 12) && (Cal.AMorPM === "PM")) { if (parseInt(intHour, 10) === 12) { Cal.Hours = 12; } else { Cal.Hours = parseInt(intHour, 10) + 12; } } else if ((TimeMode === 12) && (Cal.AMorPM === "AM")) { if (intHour === 12) { intHour -= 12; } Cal.Hours = parseInt(intHour, 10); } else if (TimeMode === 24) { Cal.Hours = parseInt(intHour, 10); } } }; Calendar.prototype.SetMinute = function (intMin) { var MaxMin = 59, MinMin = 0, SingleDigit = new RegExp("\\d"), SingleDigit2 = new RegExp("^\\d{1}$"), MinExp = new RegExp("^\\d{2}$"), strMin = 0; if ((MinExp.test(intMin) || SingleDigit.test(intMin)) && (parseInt(intMin, 10) > MaxMin)) { intMin = MinMin; } else if ((MinExp.test(intMin) || SingleDigit.test(intMin)) && (parseInt(intMin, 10) < MinMin)) { intMin = MaxMin; } strMin = intMin + ""; if (SingleDigit2.test(intMin)) { strMin = "0" + strMin; } if ((MinExp.test(intMin) || SingleDigit.test(intMin)) && (parseInt(intMin, 10) <= 59) && (parseInt(intMin, 10) >= 0)) { Cal.Minutes = strMin; } }; Calendar.prototype.SetSecond = function (intSec) { var MaxSec = 59, MinSec = 0, SingleDigit = new RegExp("\\d"), SingleDigit2 = new RegExp("^\\d{1}$"), SecExp = new RegExp("^\\d{2}$"), strSec = 0; if ((SecExp.test(intSec) || SingleDigit.test(intSec)) && (parseInt(intSec, 10) > MaxSec)) { intSec = MinSec; } else if ((SecExp.test(intSec) || SingleDigit.test(intSec)) && (parseInt(intSec, 10) < MinSec)) { intSec = MaxSec; } strSec = intSec + ""; if (SingleDigit2.test(intSec)) { strSec = "0" + strSec; } if ((SecExp.test(intSec) || SingleDigit.test(intSec)) && (parseInt(intSec, 10) <= 59) && (parseInt(intSec, 10) >= 0)) { Cal.Seconds = strSec; } }; Calendar.prototype.SetAmPm = function (pvalue) { this.AMorPM = pvalue; if (pvalue === "PM") { this.Hours = parseInt(this.Hours, 10) + 12; if (this.Hours === 24) { this.Hours = 12; } } else if (pvalue === "AM") { this.Hours -= 12; } }; Calendar.prototype.getShowHour = function () { var finalHour; if (TimeMode === 12) { if (parseInt(this.Hours, 10) === 0) { this.AMorPM = "AM"; finalHour = parseInt(this.Hours, 10) + 12; } else if (parseInt(this.Hours, 10) === 12) { this.AMorPM = "PM"; finalHour = 12; } else if (this.Hours > 12) { this.AMorPM = "PM"; if ((this.Hours - 12) < 10) { finalHour = "0" + ((parseInt(this.Hours, 10)) - 12); } else { finalHour = parseInt(this.Hours, 10) - 12; } } else { this.AMorPM = "AM"; if (this.Hours < 10) { finalHour = "0" + parseInt(this.Hours, 10); } else { finalHour = this.Hours; } } } else if (TimeMode === 24) { if (this.Hours < 10) { finalHour = "0" + parseInt(this.Hours, 10); } else { finalHour = this.Hours; } } return finalHour; }; Calendar.prototype.getShowAMorPM = function () { return this.AMorPM; }; Calendar.prototype.GetMonthName = function (IsLong) { var Month = MonthName[this.Month]; if (IsLong) { return Month; } else { return Month.substr(0, 3); } }; Calendar.prototype.GetMonDays = function() { //Get number of days in a month var DaysInMonth = [31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31]; if (Cal.IsLeapYear()) { DaysInMonth[1] = 29; } return DaysInMonth[this.Month]; }; Calendar.prototype.IsLeapYear = function () { if ((this.Year % 4) === 0) { if ((this.Year % 100 === 0) && (this.Year % 400) !== 0) { return false; } else { return true; } } else { return false; } }; Calendar.prototype.FormatDate = function (pDate) { var MonthDigit = this.Month + 1; if (PrecedeZero === true) { if ((pDate < 10) && String(pDate).length===1) //length checking added in version 2.2 { pDate = "0" + pDate; } if (MonthDigit < 10) { MonthDigit = "0" + MonthDigit; } } switch (this.Format.toUpperCase()) { case "DDMMYYYY": return (pDate + DateSeparator + MonthDigit + DateSeparator + this.Year); case "DDMMMYYYY": return (pDate + DateSeparator + this.GetMonthName(false) + DateSeparator + this.Year); case "MMDDYYYY": return (MonthDigit + DateSeparator + pDate + DateSeparator + this.Year); case "MMMDDYYYY": return (this.GetMonthName(false) + DateSeparator + pDate + DateSeparator + this.Year); case "YYYYMMDD": return (this.Year + DateSeparator + MonthDigit + DateSeparator + pDate); case "YYMMDD": return (String(this.Year).substring(2, 4) + DateSeparator + MonthDigit + DateSeparator + pDate); case "YYMMMDD": return (String(this.Year).substring(2, 4) + DateSeparator + this.GetMonthName(false) + DateSeparator + pDate); case "YYYYMMMDD": return (this.Year + DateSeparator + this.GetMonthName(false) + DateSeparator + pDate); default: return (pDate + DateSeparator + (this.Month + 1) + DateSeparator + this.Year); } }; // end Calendar prototype function GenCell(pValue, pHighLight, pColor, pClickable) { //Generate table cell with value var PValue, PCellStr, PClickable, vTimeStr; if (!pValue) { PValue = ""; } else { PValue = pValue; } if (pColor === undefined) pColor = CalBgColor; if (pClickable !== undefined){ PClickable = pClickable; } else{ PClickable = true; } if (Cal.ShowTime) { vTimeStr = ' ' + Cal.Hours + ':' + Cal.Minutes; if (Cal.ShowSeconds) { vTimeStr += ':' + Cal.Seconds; } if (TimeMode === 12) { vTimeStr += ' ' + Cal.AMorPM; } } else { vTimeStr = ""; } if (PValue !== "") { if (PClickable === true) { if (Cal.ShowTime === true) { PCellStr = "<td id='c" + PValue + "' class='calTD' style='text-align:center;cursor:pointer;background-color:"+pColor+"' onmousedown='selectDate(this," + PValue + ");'>" + PValue + "</td>"; } else { PCellStr = "<td class='calTD' style='text-align:center;cursor:pointer;background-color:" + pColor + "' onmouseover='changeBorder(this, 0);' onmouseout=\"changeBorder(this, 1, '" + pColor + "');\" onClick=\"javascript:callback('" + Cal.Ctrl + "','" + Cal.FormatDate(PValue) + "');\">" + PValue + "</td>"; } } else { PCellStr = "<td style='text-align:center;background-color:"+pColor+"' class='calTD'>"+PValue+"</td>"; } } else { PCellStr = "<td style='text-align:center;background-color:"+pColor+"' class='calTD'>&nbsp;</td>"; } return PCellStr; } function RenderCssCal(bNewCal) { if (typeof bNewCal === "undefined" || bNewCal !== true) { bNewCal = false; } var vCalHeader, vCalData, vCalTime = "", vCalClosing = "", winCalData = "", CalDate, i, j, SelectStr, vDayCount = 0, vFirstDay, WeekDayName = [],//Added version 1.7 strCell, showHour, ShowArrows = false, HourCellWidth = "35px", //cell width with seconds. SelectAm, SelectPm, funcCalback, headID, e, cssStr, style, cssText, span; calHeight = 0; // reset the window height on refresh // Set the default cursor for the calendar winCalData = "<span style='cursor:auto;'>"; vCalHeader = "<table style='background-color:"+CalBgColor+";width:200px;padding:0;margin:5px auto 5px auto'><tbody>"; //Table for Month & Year Selector vCalHeader += "<tr><td colspan='7'><table border='0' width='200px' cellpadding='0' cellspacing='0'><tr>"; //******************Month and Year selector in dropdown list************************ if (Cal.Scroller === "DROPDOWN") { vCalHeader += "<td align='center'><select name='MonthSelector' onChange='javascript:Cal.SwitchMth(this.selectedIndex);RenderCssCal();'>"; for (i = 0; i < 12; i += 1) { if (i === Cal.Month) { SelectStr = "Selected"; } else { SelectStr = ""; } vCalHeader += "<option " + SelectStr + " value=" + i + ">" + MonthName[i] + "</option>"; } vCalHeader += "</select></td>"; //Year selector vCalHeader += "<td align='center'><select name='YearSelector' size='1' onChange='javascript:Cal.SwitchYear(this.value);RenderCssCal();'>"; for (i = StartYear; i <= (dtToday.getFullYear() + EndYear); i += 1) { if (i === Cal.Year) { SelectStr = 'selected="selected"'; } else { SelectStr = ''; } vCalHeader += "<option " + SelectStr + " value=" + i + ">" + i + "</option>\n"; } vCalHeader += "</select></td>\n"; calHeight += 30; } //******************End Month and Year selector in dropdown list********************* //******************Month and Year selector in arrow********************************* else if (Cal.Scroller === "ARROW") { if (UseImageFiles) { vCalHeader += "<td><img onmousedown='javascript:Cal.DecYear();RenderCssCal();' src='"+imageFilesPath+"cal_fastreverse.gif' width='13px' height='9' onmouseover='changeBorder(this, 0)' onmouseout='changeBorder(this, 1)' style='border:1px solid white'></td>\n";//Year scroller (decrease 1 year) vCalHeader += "<td><img onmousedown='javascript:Cal.DecMonth();RenderCssCal();' src='" + imageFilesPath + "cal_reverse.gif' width='13px' height='9' onmouseover='changeBorder(this, 0)' onmouseout='changeBorder(this, 1)' style='border:1px solid white'></td>\n"; //Month scroller (decrease 1 month) vCalHeader += "<td width='70%' class='calR' style='color:"+YrSelColor+"'>"+ Cal.GetMonthName(ShowLongMonth) + " " + Cal.Year + "</td>"; //Month and Year vCalHeader += "<td><img onmousedown='javascript:Cal.IncMonth();RenderCssCal();' src='" + imageFilesPath + "cal_forward.gif' width='13px' height='9' onmouseover='changeBorder(this, 0)' onmouseout='changeBorder(this, 1)' style='border:1px solid white'></td>\n"; //Month scroller (increase 1 month) vCalHeader += "<td><img onmousedown='javascript:Cal.IncYear();RenderCssCal();' src='" + imageFilesPath + "cal_fastforward.gif' width='13px' height='9' onmouseover='changeBorder(this, 0)' onmouseout='changeBorder(this, 1)' style='border:1px solid white'></td>\n"; //Year scroller (increase 1 year) calHeight += 22; } else { vCalHeader += "<td><span id='dec_year' title='reverse year' onmousedown='javascript:Cal.DecYear();RenderCssCal();' onmouseover='changeBorder(this, 0)' onmouseout='changeBorder(this, 1)' style='border:1px solid white; color:" + YrSelColor + "'>-</span></td>";//Year scroller (decrease 1 year) vCalHeader += "<td><span id='dec_month' title='reverse month' onmousedown='javascript:Cal.DecMonth();RenderCssCal();' onmouseover='changeBorder(this, 0)' onmouseout='changeBorder(this, 1)' style='border:1px solid white'>&lt;</span></td>\n";//Month scroller (decrease 1 month) vCalHeader += "<td width='70%' class='calR' style='color:" + YrSelColor + "'>" + Cal.GetMonthName(ShowLongMonth) + " " + Cal.Year + "</td>\n"; //Month and Year vCalHeader += "<td><span id='inc_month' title='forward month' onmousedown='javascript:Cal.IncMonth();RenderCssCal();' onmouseover='changeBorder(this, 0)' onmouseout='changeBorder(this, 1)' style='border:1px solid white'>&gt;</span></td>\n";//Month scroller (increase 1 month) vCalHeader += "<td><span id='inc_year' title='forward year' onmousedown='javascript:Cal.IncYear();RenderCssCal();' onmouseover='changeBorder(this, 0)' onmouseout='changeBorder(this, 1)' style='border:1px solid white; color:" + YrSelColor + "'>+</span></td>\n";//Year scroller (increase 1 year) calHeight += 22; } } vCalHeader += "</tr></table></td></tr>"; //******************End Month and Year selector in arrow****************************** //Calendar header shows Month and Year if (ShowMonthYear && Cal.Scroller === "DROPDOWN") { vCalHeader += "<tr><td colspan='7' class='calR' style='color:" + MonthYearColor + "'>" + Cal.GetMonthName(ShowLongMonth) + " " + Cal.Year + "</td></tr>"; calHeight += 19; } //Week day header vCalHeader += "<tr><td colspan=\"7\"><table style='border-spacing:1px;border-collapse:separate;'><tr>"; if (MondayFirstDay === true) { WeekDayName = WeekDayName2; } else { WeekDayName = WeekDayName1; } for (i = 0; i < 7; i += 1) { vCalHeader += "<td style='background-color:"+WeekHeadColor+";width:"+CellWidth+"px;color:#FFFFFF' class='calTD'>" + WeekDayName[i].substr(0, WeekChar) + "</td>"; } calHeight += 19; vCalHeader += "</tr>"; //Calendar detail CalDate = new Date(Cal.Year, Cal.Month); CalDate.setDate(1); vFirstDay = CalDate.getDay(); //Added version 1.7 if (MondayFirstDay === true) { vFirstDay -= 1; if (vFirstDay === -1) { vFirstDay = 6; } } //Added version 1.7 vCalData = "<tr>"; calHeight += 19; for (i = 0; i < vFirstDay; i += 1) { vCalData = vCalData + GenCell(); vDayCount = vDayCount + 1; } //Added version 1.7 for (j = 1; j <= Cal.GetMonDays(); j += 1) { if ((vDayCount % 7 === 0) && (j > 1)) { vCalData = vCalData + "<tr>"; } vDayCount = vDayCount + 1; //added version 2.1.2 if (DisableBeforeToday === true && ((j < dtToday.getDate()) && (Cal.Month === dtToday.getMonth()) && (Cal.Year === dtToday.getFullYear()) || (Cal.Month < dtToday.getMonth()) && (Cal.Year === dtToday.getFullYear()) || (Cal.Year < dtToday.getFullYear()))) { strCell = GenCell(j, false, DisableColor, false);//Before today's date is not clickable } //if End Year + Current Year = Cal.Year. Disable. else if (Cal.Year > (dtToday.getFullYear()+EndYear)) { strCell = GenCell(j, false, DisableColor, false); } else if ((j === dtToday.getDate()) && (Cal.Month === dtToday.getMonth()) && (Cal.Year === dtToday.getFullYear())) { strCell = GenCell(j, true, TodayColor);//Highlight today's date } else { if ((j === selDate.getDate()) && (Cal.Month === selDate.getMonth()) && (Cal.Year === selDate.getFullYear())){ //modified version 1.7 strCell = GenCell(j, true, SelDateColor); } else { if (MondayFirstDay === true) { if (vDayCount % 7 === 0) { strCell = GenCell(j, false, SundayColor); } else if ((vDayCount + 1) % 7 === 0) { strCell = GenCell(j, false, SaturdayColor); } else { strCell = GenCell(j, null, WeekDayColor); } } else { if (vDayCount % 7 === 0) { strCell = GenCell(j, false, SaturdayColor); } else if ((vDayCount + 6) % 7 === 0) { strCell = GenCell(j, false, SundayColor); } else { strCell = GenCell(j, null, WeekDayColor); } } } } vCalData = vCalData + strCell; if ((vDayCount % 7 === 0) && (j < Cal.GetMonDays())) { vCalData = vCalData + "</tr>"; calHeight += 19; } } // finish the table proper if (vDayCount % 7 !== 0) { while (vDayCount % 7 !== 0) { vCalData = vCalData + GenCell(); vDayCount = vDayCount + 1; } } vCalData = vCalData + "</table></td></tr>"; //Time picker if (Cal.ShowTime === true) { showHour = Cal.getShowHour(); if (Cal.ShowSeconds === false && TimeMode === 24) { ShowArrows = true; HourCellWidth = "10px"; } vCalTime = "<tr><td colspan='7' style=\"text-align:center;\"><table border='0' width='199px' cellpadding='0' cellspacing='0'><tbody><tr><td height='5px' width='" + HourCellWidth + "'>&nbsp;</td>"; if (ShowArrows && UseImageFiles) //this is where the up and down arrow control the hour. { vCalTime += "<td style='vertical-align:middle;'><table cellspacing='0' cellpadding='0' style='line-height:0pt;width:100%;'><tr><td style='text-align:center;'><img onclick='nextStep(\"Hour\", \"plus\");' onmousedown='startSpin(\"Hour\", \"plus\");' onmouseup='stopSpin();' src='" + imageFilesPath + "cal_plus.gif' width='13px' height='9px' onmouseover='changeBorder(this, 0)' onmouseout='changeBorder(this, 1)' style='border:1px solid white'></td></tr><tr><td style='text-align:center;'><img onclick='nextStep(\"Hour\", \"minus\");' onmousedown='startSpin(\"Hour\", \"minus\");' onmouseup='stopSpin();' src='" + imageFilesPath + "cal_minus.gif' width='13px' height='9px' onmouseover='changeBorder(this, 0)' onmouseout='changeBorder(this, 1)' style='border:1px solid white'></td></tr></table></td>\n"; } vCalTime += "<td width='22px'><input type='text' name='hour' maxlength=2 size=1 style=\"WIDTH:22px\" value=" + showHour + " onkeyup=\"javascript:Cal.SetHour(this.value)\">"; vCalTime += "</td><td style='font-weight:bold;text-align:center;'>:</td><td width='22px'>"; vCalTime += "<input type='text' name='minute' maxlength=2 size=1 style=\"WIDTH: 22px\" value=" + Cal.Minutes + " onkeyup=\"javascript:Cal.SetMinute(this.value)\">"; if (Cal.ShowSeconds) { vCalTime += "</td><td style='font-weight:bold;'>:</td><td width='22px'>"; vCalTime += "<input type='text' name='second' maxlength=2 size=1 style=\"WIDTH: 22px\" value=" + Cal.Seconds + " onkeyup=\"javascript:Cal.SetSecond(parseInt(this.value,10))\">"; } if (TimeMode === 12) { SelectAm = (Cal.AMorPM === "AM") ? "Selected" : ""; SelectPm = (Cal.AMorPM === "PM") ? "Selected" : ""; vCalTime += "</td><td>"; vCalTime += "<select name=\"ampm\" onChange=\"javascript:Cal.SetAmPm(this.options[this.selectedIndex].value);\">\n"; vCalTime += "<option " + SelectAm + " value=\"AM\">AM</option>"; vCalTime += "<option " + SelectPm + " value=\"PM\">PM<option>"; vCalTime += "</select>"; } if (ShowArrows && UseImageFiles) //this is where the up and down arrow to change the "Minute". { vCalTime += "</td>\n<td style='vertical-align:middle;'><table cellspacing='0' cellpadding='0' style='line-height:0pt;width:100%'><tr><td style='text-align:center;'><img onclick='nextStep(\"Minute\", \"plus\");' onmousedown='startSpin(\"Minute\", \"plus\");' onmouseup='stopSpin();' src='" + imageFilesPath + "cal_plus.gif' width='13px' height='9px' onmouseover='changeBorder(this, 0)' onmouseout='changeBorder(this, 1)' style='border:1px solid white'></td></tr><tr><td style='text-align:center;'><img onmousedown='startSpin(\"Minute\", \"minus\");' onmouseup='stopSpin();' onclick='nextStep(\"Minute\",\"minus\");' src='" + imageFilesPath + "cal_minus.gif' width='13px' height='9px' onmouseover='changeBorder(this, 0)' onmouseout='changeBorder(this, 1)' style='border:1px solid white'></td></tr></table>"; } vCalTime += "</td>\n<td align='right' valign='bottom' width='" + HourCellWidth + "px'></td></tr>"; vCalTime += "<tr><td colspan='7' style=\"text-align:center;\"><input style='width:60px;font-size:12px;' onClick='javascript:closewin(\"" + Cal.Ctrl + "\");' type=\"button\" value=\"OK\">&nbsp;<input style='width:60px;font-size:12px;' onClick='javascript: winCal.style.visibility = \"hidden\"' type=\"button\" value=\"Cancel\"></td></tr>"; } else //if not to show time. { vCalTime += "\n<tr>\n<td colspan='7' style=\"text-align:right;\">"; //close button if (UseImageFiles) { vCalClosing += "<img onmousedown='javascript:closewin(\"" + Cal.Ctrl + "\"); stopSpin();' src='"+imageFilesPath+"cal_close.gif' width='16px' height='16px' onmouseover='changeBorder(this,0)' onmouseout='changeBorder(this, 1)' style='border:1px solid white'></td>"; } else { vCalClosing += "<span id='close_cal' title='close'onmousedown='javascript:closewin(\"" + Cal.Ctrl + "\");stopSpin();' onmouseover='changeBorder(this, 0)'onmouseout='changeBorder(this, 1)' style='border:1px solid white; font-family: Arial;font-size: 10pt;'>x</span></td>"; } vCalClosing += "</tr>"; } vCalClosing += "</tbody></table></td></tr>"; calHeight += 31; vCalClosing += "</tbody></table>\n</span>"; //end time picker funcCalback = "function callback(id, datum) {"; funcCalback += " var CalId = document.getElementById(id);if (datum=== 'undefined') { var d = new Date(); datum = d.getDate() + '/' +(d.getMonth()+1) + '/' + d.getFullYear(); } window.calDatum=datum;CalId.value=datum;"; funcCalback += " if(Cal.ShowTime){"; funcCalback += " CalId.value+=' '+Cal.getShowHour()+':'+Cal.Minutes;"; funcCalback += " if (Cal.ShowSeconds) CalId.value+=':'+Cal.Seconds;"; funcCalback += " if (TimeMode === 12) CalId.value+=''+Cal.getShowAMorPM();"; funcCalback += "}if(CalId.onchange===true) CalId.onchange();CalId.focus();winCal.style.visibility='hidden';}"; // determines if there is enough space to open the cal above the position where it is called if (ypos > calHeight) { ypos = ypos - calHeight; } if (!winCal) { headID = document.getElementsByTagName("head")[0]; // add javascript function to the span cal e = document.createElement("script"); e.type = "text/javascript"; e.language = "javascript"; e.text = funcCalback; headID.appendChild(e); // add stylesheet to the span cal cssStr = ".calTD {font-family: verdana; font-size: 12px; text-align: center; border:0; }\n"; cssStr += ".calR {font-family: verdana; font-size: 12px; text-align: center; font-weight: bold;}"; style = document.createElement("style"); style.type = "text/css"; style.rel = "stylesheet"; if (style.styleSheet) { // IE style.styleSheet.cssText = cssStr; } else { // w3c cssText = document.createTextNode(cssStr); style.appendChild(cssText); } headID.appendChild(style); // create the outer frame that allows the cal. to be moved span = document.createElement("span"); span.id = calSpanID; span.style.position = "absolute"; span.style.left = (xpos + CalPosOffsetX) + 'px'; span.style.top = (ypos - CalPosOffsetY) + 'px'; span.style.width = CalWidth + 'px'; span.style.border = "solid 1pt " + SpanBorderColor; span.style.padding = "0"; span.style.cursor = "move"; span.style.backgroundColor = SpanBgColor; span.style.zIndex = 100; document.body.appendChild(span); winCal = document.getElementById(calSpanID); } else { winCal.style.visibility = "visible"; winCal.style.Height = calHeight; // set the position for a new calendar only if (bNewCal === true) { winCal.style.left = (xpos + CalPosOffsetX) + 'px'; winCal.style.top = (ypos - CalPosOffsetY) + 'px'; } } winCal.innerHTML = winCalData + vCalHeader + vCalData + vCalTime + vCalClosing; return true; } function NewCssCal(pCtrl, pFormat, pScroller, pShowTime, pTimeMode, pShowSeconds) { // get current date and time dtToday = new Date(); Cal = new Calendar(dtToday); if (pShowTime !== undefined) { if (pShowTime) { Cal.ShowTime = true; } else { Cal.ShowTime = false; } if (pTimeMode) { pTimeMode = parseInt(pTimeMode, 10); } if (pTimeMode === 12 || pTimeMode === 24) { TimeMode = pTimeMode; } else { TimeMode = 24; } if (pShowSeconds !== undefined) { if (pShowSeconds) { Cal.ShowSeconds = true; } else { Cal.ShowSeconds = false; } } else { Cal.ShowSeconds = false; } } if (pCtrl !== undefined) { Cal.Ctrl = pCtrl; } if (pFormat !== undefined) { Cal.Format = pFormat.toUpperCase(); } else { Cal.Format = "MMDDYYYY"; } if (pScroller !== undefined) { if (pScroller.toUpperCase() === "ARROW") { Cal.Scroller = "ARROW"; } else { Cal.Scroller = "DROPDOWN"; } } exDateTime = document.getElementById(pCtrl).value; //Existing Date Time value in textbox. if (exDateTime) { //Parse existing Date String var Sp1 = exDateTime.indexOf(DateSeparator, 0),//Index of Date Separator 1 Sp2 = exDateTime.indexOf(DateSeparator, parseInt(Sp1, 10) + 1),//Index of Date Separator 2 tSp1,//Index of Time Separator 1 tSp2,//Index of Time Separator 2 strMonth, strDate, strYear, intMonth, YearPattern, strHour, strMinute, strSecond, winHeight, offset = parseInt(Cal.Format.toUpperCase().lastIndexOf("M"), 10) - parseInt(Cal.Format.toUpperCase().indexOf("M"), 10) - 1, strAMPM = ""; //parse month if (Cal.Format.toUpperCase() === "DDMMYYYY" || Cal.Format.toUpperCase() === "DDMMMYYYY") { if (DateSeparator === "") { strMonth = exDateTime.substring(2, 4 + offset); strDate = exDateTime.substring(0, 2); strYear = exDateTime.substring(4 + offset, 8 + offset); } else { if (exDateTime.indexOf("D*") !== -1) { //DTG strMonth = exDateTime.substring(8, 11); strDate = exDateTime.substring(0, 2); strYear = "20" + exDateTime.substring(11, 13); //Hack, nur für Jahreszahlen ab 2000 } else { strMonth = exDateTime.substring(Sp1 + 1, Sp2); strDate = exDateTime.substring(0, Sp1); strYear = exDateTime.substring(Sp2 + 1, Sp2 + 5); } } } else if (Cal.Format.toUpperCase() === "MMDDYYYY" || Cal.Format.toUpperCase() === "MMMDDYYYY"){ if (DateSeparator === ""){ strMonth = exDateTime.substring(0, 2 + offset); strDate = exDateTime.substring(2 + offset, 4 + offset); strYear = exDateTime.substring(4 + offset, 8 + offset); } else{ strMonth = exDateTime.substring(0, Sp1); strDate = exDateTime.substring(Sp1 + 1, Sp2); strYear = exDateTime.substring(Sp2 + 1, Sp2 + 5); } } else if (Cal.Format.toUpperCase() === "YYYYMMDD" || Cal.Format.toUpperCase() === "YYYYMMMDD") { if (DateSeparator === ""){ strMonth = exDateTime.substring(4, 6 + offset); strDate = exDateTime.substring(6 + offset, 8 + offset); strYear = exDateTime.substring(0, 4); } else{ strMonth = exDateTime.substring(Sp1 + 1, Sp2); strDate = exDateTime.substring(Sp2 + 1, Sp2 + 3); strYear = exDateTime.substring(0, Sp1); } } else if (Cal.Format.toUpperCase() === "YYMMDD" || Cal.Format.toUpperCase() === "YYMMMDD") { if (DateSeparator === "") { strMonth = exDateTime.substring(2, 4 + offset); strDate = exDateTime.substring(4 + offset, 6 + offset); strYear = exDateTime.substring(0, 2); } else { strMonth = exDateTime.substring(Sp1 + 1, Sp2); strDate = exDateTime.substring(Sp2 + 1, Sp2 + 3); strYear = exDateTime.substring(0, Sp1); } } if (isNaN(strMonth)){ intMonth = Cal.GetMonthIndex(strMonth); } else{ intMonth = parseInt(strMonth, 10) - 1; } if ((parseInt(intMonth, 10) >= 0) && (parseInt(intMonth, 10) < 12)) { Cal.Month = intMonth; } //end parse month //parse year YearPattern = /^\d{4}$/; if (YearPattern.test(strYear)) { if ((parseInt(strYear, 10)>=StartYear) && (parseInt(strYear, 10)<= (dtToday.getFullYear()+EndYear))) Cal.Year = parseInt(strYear, 10); } //end parse year //parse Date if ((parseInt(strDate, 10) <= Cal.GetMonDays()) && (parseInt(strDate, 10) >= 1)) { Cal.Date = strDate; } //end parse Date //parse time if (Cal.ShowTime === true) { //parse AM or PM if (TimeMode === 12) { strAMPM = exDateTime.substring(exDateTime.length - 2, exDateTime.length); Cal.AMorPM = strAMPM; } tSp1 = exDateTime.indexOf(":", 0); tSp2 = exDateTime.indexOf(":", (parseInt(tSp1, 10) + 1)); if (tSp1 > 0) { strHour = exDateTime.substring(tSp1, tSp1 - 2); Cal.SetHour(strHour); strMinute = exDateTime.substring(tSp1 + 1, tSp1 + 3); Cal.SetMinute(strMinute); strSecond = exDateTime.substring(tSp2 + 1, tSp2 + 3); Cal.SetSecond(strSecond); } else if (exDateTime.indexOf("D*") !== -1) { //DTG strHour = exDateTime.substring(2, 4); Cal.SetHour(strHour); strMinute = exDateTime.substring(4, 6); Cal.SetMinute(strMinute); } } } selDate = new Date(Cal.Year, Cal.Month, Cal.Date);//version 1.7 RenderCssCal(true); } function closewin(id) { if (Cal.ShowTime === true) { var MaxYear = dtToday.getFullYear() + EndYear; var beforeToday = (Cal.Date < dtToday.getDate()) && (Cal.Month === dtToday.getMonth()) && (Cal.Year === dtToday.getFullYear()) || (Cal.Month < dtToday.getMonth()) && (Cal.Year === dtToday.getFullYear()) || (Cal.Year < dtToday.getFullYear()); if ((Cal.Year <= MaxYear) && (Cal.Year >= StartYear) && (Cal.Month === selDate.getMonth()) && (Cal.Year === selDate.getFullYear())) { if (DisableBeforeToday === true) { if (beforeToday === false) { callback(id, Cal.FormatDate(Cal.Date)); } } else callback(id, Cal.FormatDate(Cal.Date)); } } var CalId = document.getElementById(id); CalId.focus(); winCal.style.visibility = 'hidden'; } function changeBorder(element, col, oldBgColor) { if (col === 0) { element.style.background = HoverColor; element.style.borderColor = "black"; element.style.cursor = "pointer"; } else { if (oldBgColor) { element.style.background = oldBgColor; } else { element.style.background = "white"; } element.style.borderColor = "white"; element.style.cursor = "auto"; } } function selectDate(element, date) { Cal.Date = date; selDate = new Date(Cal.Year, Cal.Month, Cal.Date); element.style.background = SelDateColor; RenderCssCal(); } function pickIt(evt) { var objectID, dom, de, b; // accesses the element that generates the event and retrieves its ID if (document.addEventListener) { // w3c objectID = evt.target.id; if (objectID.indexOf(calSpanID) !== -1) { dom = document.getElementById(objectID); cnLeft = evt.pageX; cnTop = evt.pageY; if (dom.offsetLeft) { cnLeft = (cnLeft - dom.offsetLeft); cnTop = (cnTop - dom.offsetTop); } } // get mouse position on click xpos = (evt.pageX); ypos = (evt.pageY); } else { // IE objectID = event.srcElement.id; cnLeft = event.offsetX; cnTop = (event.offsetY); // get mouse position on click de = document.documentElement; b = document.body; xpos = event.clientX + (de.scrollLeft || b.scrollLeft) - (de.clientLeft || 0); ypos = event.clientY + (de.scrollTop || b.scrollTop) - (de.clientTop || 0); } // verify if this is a valid element to pick if (objectID.indexOf(calSpanID) !== -1) { domStyle = document.getElementById(objectID).style; } if (domStyle) { domStyle.zIndex = 100; return false; } else { domStyle = null; return; } } function dragIt(evt) { if (domStyle) { if (document.addEventListener) { //for IE domStyle.left = (event.clientX - cnLeft + document.body.scrollLeft) + 'px'; domStyle.top = (event.clientY - cnTop + document.body.scrollTop) + 'px'; } else { //Firefox domStyle.left = (evt.clientX - cnLeft + document.body.scrollLeft) + 'px'; domStyle.top = (evt.clientY - cnTop + document.body.scrollTop) + 'px'; } } } // performs a single increment or decrement function nextStep(whatSpinner, direction) { if (whatSpinner === "Hour") { if (direction === "plus") { Cal.SetHour(Cal.Hours + 1); RenderCssCal(); } else if (direction === "minus") { Cal.SetHour(Cal.Hours - 1); RenderCssCal(); } } else if (whatSpinner === "Minute") { if (direction === "plus") { Cal.SetMinute(parseInt(Cal.Minutes, 10) + 1); RenderCssCal(); } else if (direction === "minus") { Cal.SetMinute(parseInt(Cal.Minutes, 10) - 1); RenderCssCal(); } } } // starts the time spinner function startSpin(whatSpinner, direction) { document.thisLoop = setInterval(function () { nextStep(whatSpinner, direction); }, 125); //125 ms } //stops the time spinner function stopSpin() { clearInterval(document.thisLoop); } function dropIt() { stopSpin(); if (domStyle) { domStyle = null; } } // Default events configuration document.onmousedown = pickIt; document.onmousemove = dragIt; document.onmouseup = dropIt;
JavaScript
function setCheckboxes(the_form, id, do_check) { var elts = (typeof(document.forms[the_form].elements[id]) != 'undefined') ? document.forms[the_form].elements[id] : 0; var elts_cnt = (typeof(elts.length) != 'undefined') ? elts.length : 0; if (elts_cnt) { for (var i = 0; i < elts_cnt; i++) { elts[i].checked = do_check; } } else { elts.checked = do_check; } return true; } function check_chose(id, arid, the_form) { var n = $('#'+id+':checked').val(); if(n) setCheckboxes(the_form, arid, true); else setCheckboxes(the_form, arid, false); } function verify_del() { return window.confirm("Bạn có muốn xóa các mục này không?\nVui lòng xác nhận."); } function verify_delpage() { return window.confirm("Bạn muốn xóa trang này?\nVui lòng xác nhận."); } function setCheckboxValue(id) { if(id.checked) { id.value = 1; }else{ id.value = 0; } } function set_action(form_name,action){ document.forms[form_name].action=action; } function verify_copy(str) { return window.confirm(str); }
JavaScript
Calendar.LANG("it", "Italiano", { fdow: 1, // first day of week for this locale; 0 = Sunday, 1 = Monday, etc. goToday: "Vai a oggi", today: "Oggi", // appears in bottom bar wk: "set", weekend: "0,6", // 0 = Sunday, 1 = Monday, etc. AM: "am", PM: "pm", mn : [ "Gennaio", "Febbraio", "Marzo", "Aprile", "Maggio", "Giugno", "Luglio", "Agosto", "Settembre", "Ottobre", "Novembre", "Dicembre" ], smn : [ "Gen", "Feb", "Mar", "Apr", "Mag", "Giu", "Lug", "Ago", "Set", "Ott", "Nov", "Dic" ], dn : [ "Domenica", "Lunedì", "Martedì", "Mercoledì", "Giovedi", "Venerdì", "Sabato", "Domenica" ], sdn : [ "Do", "Lu", "Ma", "Me", "Gi", "Ve", "Sa", "Do" ] });
JavaScript
Calendar.LANG("de", "Deutsch", { fdow: 1, // first day of week for this locale; 0 = Sunday, 1 = Monday, etc. goToday : "Heute ausw\u00e4hlen", today: "Heute", // appears in bottom bar wk: "wk", weekend: "0,6", // 0 = Sunday, 1 = Monday, etc. AM: "am", PM: "pm", mn : [ "Januar", "Februar", "M\u00e4rz", "April", "Mai", "Juni", "Juli", "August", "September", "Oktober", "November", "Dezember" ], smn : [ "Jan", "Feb", "M\u00e4r", "Apr", "May", "Jun", "Jul", "Aug", "Sep", "Okt", "Nov", "Dez" ], dn : [ "Sonntag", "Montag", "Dienstag", "Mittwoch", "Donnerstag", "Freitag", "Samstag", "Sonntag" ], sdn : [ "So", "Mo", "Di", "Mi", "Do", "Fr", "Sa", "So" ] });
JavaScript
Calendar.LANG("jp", "Japanese", { fdow: 1, // 地元の週の初めの日; 0 = 日曜日, 1 = 月曜日, 等. goToday: "本日へ", today: "本日", // ボットンバーに表示 wk: "週", weekend: "0,6", // 0 = 日曜日, 1 = 月曜日, 等. AM: "am", PM: "pm", mn : [ "1月", "2月", "3月", "4月", "5月", "6月", "7月", "8月", "9月", "10月", "11月", "12月" ], smn : [ "1月", "2月", "3月", "4月", "5月", "6月", "7月", "8月", "9月", "10月", "11月", "12月" ], dn : [ "日曜日", "月曜日", "火曜日", "水曜日", "木曜日", "金曜日", "土曜日", "日曜日" ], sdn : [ "日", "月", "火", "水", "木", "金", "土", "日" ] });
JavaScript
// autor: Piotr kwiatkowski // www: http://pasjonata.net Calendar.LANG("pl", "Polish", { fdow: 1, // pierwszy dzień tygodnia; 0 = Niedziela, 1 = Poniedziałek, itd. goToday: "Idzie Dzisiaj", today: "Dziś", wk: "wk", weekend: "0,6", // 0 = Niedziela, 1 = Poniedziałek, itd. AM: "am", PM: "pm", mn : [ "Styczeń", "Luty", "Marzec", "Kwiecień", "Maj", "Czerwiec", "Lipiec", "Sierpień", "Wrzesień", "Październik", "Listopad", "Grudzień" ], smn : [ "Sty", "Lut", "Mar", "Kwi", "Maj", "Cze", "Lip", "Sie", "Wrz", "Paź", "Lis", "Gru" ], dn : [ "Niedziela", "Poniedziałek", "Wtorek", "Środa", "Czwartek", "Piątek", "Sobota", "Niedziela" ], sdn : [ "Ni", "Po", "Wt", "Śr", "Cz", "Pi", "So", "Ni" ] });
JavaScript
Calendar.LANG("ru", "русский", { fdow: 1, // first day of week for this locale; 0 = Sunday, 1 = Monday, etc. goToday: "Сегодня", today: "Сегодня", // appears in bottom bar wk: "нед", weekend: "0,6", // 0 = Sunday, 1 = Monday, etc. AM: "am", PM: "pm", mn : [ "январь", "февраль", "март", "апрель", "май", "июнь", "июль", "август", "сентябрь", "октябрь", "ноябрь", "декабрь" ], smn : [ "янв", "фев", "мар", "апр", "май", "июн", "июл", "авг", "сен", "окт", "ноя", "дек" ], dn : [ "воскресенье", "понедельник", "вторник", "среда", "четверг", "пятница", "суббота", "воскресенье" ], sdn : [ "вск", "пон", "втр", "срд", "чет", "пят", "суб", "вск" ] });
JavaScript
Calendar.LANG("fr", "Français", { fdow: 1, // first day of week for this locale; 0 = Sunday, 1 = Monday, etc. goToday : "Aujourd'hui", today: "Aujourd'hui", // appears in bottom bar wk: "sm.", weekend: "0,6", // 0 = Sunday, 1 = Monday, etc. AM: "am", PM: "pm", mn : [ "Janvier", "Février", "Mars", "Avril", "Mai", "Juin", "Juillet", "Août", "Septembre", "Octobre", "Novembre", "Décembre" ], smn : [ "Jan", "Fév", "Mar", "Avr", "Mai", "Juin", "Juil", "Aou", "Sep", "Oct", "Nov", "Déc" ], dn : [ "Dimanche", "Lundi", "Mardi", "Mercredi", "Jeudi", "Vendredi", "Samedi", "Dimanche" ], sdn : [ "Di", "Lu", "Ma", "Me", "Je", "Ve", "Sa", "Di" ] });
JavaScript
Calendar.LANG("cz", "Czech", { fdow: 1, // first day of week for this locale; 0 = Sunday, 1 = Monday, etc. goToday: "Ukaž dnešek", today: "Dnes", // appears in bottom bar wk: "týd", weekend: "0,6", // 0 = Sunday, 1 = Monday, etc. AM: "am", PM: "pm", mn : [ "Leden", "Únor", "Březen", "Duben", "Květen", "Červen", "Červenec", "Srpen", "Září", "Říjen", "Listopad", "Prosinec" ], smn : [ "Led", "Úno", "Bře", "Dub", "Kvě", "Črn", "Črc", "Srp", "Zář", "Říj", "Lis", "Pro" ], dn : [ "Neděle", "Pondělí", "Úterý", "Středa", "Čtvrtek", "Pátek", "Sobota", "Neděle" ], sdn : [ "Ne", "Po", "Út", "St", "Čt", "Pá", "So", "Ne" ] });
JavaScript
Calendar.LANG("en", "English", { fdow: 1, // first day of week for this locale; 0 = Sunday, 1 = Monday, etc. goToday: "Go Today", today: "Today", // appears in bottom bar wk: "wk", weekend: "0,6", // 0 = Sunday, 1 = Monday, etc. AM: "am", PM: "pm", mn : [ "January", "February", "March", "April", "May", "June", "July", "August", "September", "October", "November", "December" ], smn : [ "Jan", "Feb", "Mar", "Apr", "May", "Jun", "Jul", "Aug", "Sep", "Oct", "Nov", "Dec" ], dn : [ "Sunday", "Monday", "Tuesday", "Wednesday", "Thursday", "Friday", "Saturday", "Sunday" ], sdn : [ "Su", "Mo", "Tu", "We", "Th", "Fr", "Sa", "Su" ] });
JavaScript
Calendar.LANG("es", "Español", { fdow: 1, // first day of week for this locale; 0 = Sunday, 1 = Monday, etc. goToday: "Ir a Hoy", today: "Hoy", // appears in bottom bar wk: "sem", weekend: "0,6", // 0 = Sunday, 1 = Monday, etc. AM: "am", PM: "pm", mn : [ "Enero", "Febrero", "Marzo", "Abril", "Mayo", "Junio", "Julio", "Agosto", "Septiembre", "Octubre", "Noviembre", "Diciembre" ], smn : [ "Ene", "Feb", "Mar", "Abr", "May", "Jun", "Jul", "Ago", "Sep", "Oct", "Nov", "Dic" ], dn : [ "Domingo", "Lunes", "Martes", "Miercoles", "Jueves", "Viernes", "Sabado", "Domingo" ], sdn : [ "Do", "Lu", "Ma", "Mi", "Ju", "Vi", "Sa", "Do" ] });
JavaScript
Calendar.LANG("ro", "Română", { fdow: 1, // first day of week for this locale; 0 = Sunday, 1 = Monday, etc. goToday: "Astăzi", today: "Astăzi", // appears in bottom bar wk: "săp.", weekend: "0,6", // 0 = Sunday, 1 = Monday, etc. AM: "am", PM: "pm", mn : [ "Ianuarie", "Februarie", "Martie", "Aprilie", "Mai", "Iunie", "Iulie", "August", "Septembrie", "Octombrie", "Noiembrie", "Decembrie" ], smn : [ "Ian", "Feb", "Mar", "Apr", "Mai", "Iun", "Iul", "Aug", "Sep", "Oct", "Noi", "Dec" ], dn : [ "Duminică", "Luni", "Marţi", "Miercuri", "Joi", "Vineri", "Sâmbătă", "Duminică" ], sdn : [ "Du", "Lu", "Ma", "Mi", "Jo", "Vi", "Sâ", "Du" ] });
JavaScript
Calendar.LANG("cn", "中文", { fdow: 1, // first day of week for this locale; 0 = Sunday, 1 = Monday, etc. goToday: "今天", today: "今天", // appears in bottom bar wk: "周", weekend: "0,6", // 0 = Sunday, 1 = Monday, etc. AM: "AM", PM: "PM", mn : [ "一月", "二月", "三月", "四月", "五月", "六月", "七月", "八月", "九月", "十月", "十一月", "十二月"], smn : [ "一月", "二月", "三月", "四月", "五月", "六月", "七月", "八月", "九月", "十月", "十一月", "十二月"], dn : [ "日", "一", "二", "三", "四", "五", "六", "日" ], sdn : [ "日", "一", "二", "三", "四", "五", "六", "日" ] });
JavaScript
Calendar.LANG("pt", "Portuguese", { fdow: 1, // primeiro dia da semana para esse local; 0 = Domingo, 1 = Segunda, etc. goToday: "Dia de Hoje", today: "Hoje", wk: "sm", weekend: "0,6", // 0 = Domingo, 1 = Segunda, etc. AM: "am", PM: "pm", mn : [ "Janeiro", "Fevereiro", "Março", "Abril", "Maio", "Junho", "Julho", "Agosto", "Setembro", "Outubro", "Novembro", "Dezembro" ], smn : [ "Jan", "Fev", "Mar", "Abr", "Mai", "Jun", "Jul", "Ago", "Set", "Out", "Nov", "Dez" ], dn : [ "Domingo", "Segunda", "Terça", "Quarta", "Quinta", "Sexta", "Sábado", "Domingo" ], sdn : [ "Dom", "Seg", "Ter", "Qua", "Qui", "Sex", "Sab", "Dom" ] });
JavaScript
/* * Inline Form Validation Engine 2.0 Beta, jQuery plugin * * Copyright(c) 2010, Cedric Dugas * http://www.position-absolute.com * * 2.0 Rewrite by Olivier Refalo * http://www.crionics.com * * Form validation engine allowing custom regex rules to be added. * Licensed under the MIT License */ (function($) { var methods = { /** * Kind of the constructor, called before any action * @param {Map} user options */ init: function(options) { var form = this; if (form.data('jqv') === undefined || form.data('jqv') == null ) { methods._saveOptions(form, options); // bind all formError elements to close on click $(".formError").live("click", function() { $(this).fadeOut(150, function() { // remove prompt once invisible $(this).remove(); }); }); } }, /** * Attachs jQuery.validationEngine to form.submit and field.blur events * Takes an optional params: a list of options * ie. jQuery("#formID1").validationEngine('attach', {promptPosition : "centerRight"}); */ attach: function(userOptions) { var form = this; var options; if(userOptions) options = methods._saveOptions(form, userOptions); else options = form.data('jqv'); if (!options.binded) { if(options.bindMethod == "bind"){ // bind fields form.find("[class*=validate]").not("[type=checkbox]").bind(options.validationEventTrigger, methods._onFieldEvent); form.find("[class*=validate][type=checkbox]").bind("click", methods._onFieldEvent); // bind form.submit form.bind("submit", methods._onSubmitEvent); }else if(options.bindMethod == "live"){ // bind fields with LIVE (for persistant state) form.find("[class*=validate]").not("[type=checkbox]").live(options.validationEventTrigger, methods._onFieldEvent); form.find("[class*=validate][type=checkbox]").live("click", methods._onFieldEvent); // bind form.submit form.live("submit", methods._onSubmitEvent); } options.binded = true; } }, /** * Unregisters any bindings that may point to jQuery.validaitonEngine */ detach: function() { var form = this; var options = form.data('jqv'); if (options.binded) { // unbind fields form.find("[class*=validate]").not("[type=checkbox]").unbind(options.validationEventTrigger, methods._onFieldEvent); form.find("[class*=validate][type=checkbox]").unbind("click", methods._onFieldEvent); // unbind form.submit form.unbind("submit", methods.onAjaxFormComplete); // unbind live fields (kill) form.find("[class*=validate]").not("[type=checkbox]").die(options.validationEventTrigger, methods._onFieldEvent); form.find("[class*=validate][type=checkbox]").die("click", methods._onFieldEvent); // unbind form.submit form.die("submit", methods.onAjaxFormComplete); form.removeData('jqv'); } }, /** * Validates the form fields, shows prompts accordingly. * Note: There is no ajax form validation with this method, only field ajax validation are evaluated * * @return true if the form validates, false if it fails */ validate: function() { return methods._validateFields(this); }, /** * Validates one field, shows prompt accordingly. * Note: There is no ajax form validation with this method, only field ajax validation are evaluated * * @return true if the form validates, false if it fails */ validateField: function(el) { var options = $(this).data('jqv'); return methods._validateField($(el), options); }, /** * Validates the form fields, shows prompts accordingly. * Note: this methods performs fields and form ajax validations(if setup) * * @return true if the form validates, false if it fails, undefined if ajax is used for form validation */ validateform: function() { return methods._onSubmitEvent(this); }, /** * Displays a prompt on a element. * Note that the element needs an id! * * @param {String} promptText html text to display type * @param {String} type the type of bubble: 'pass' (green), 'load' (black) anything else (red) * @param {String} possible values topLeft, topRight, bottomLeft, centerRight, bottomRight */ showPrompt: function(promptText, type, promptPosition, showArrow) { var form = this.closest('form'); var options = form.data('jqv'); // No option, take default one if(!options) options = methods._saveOptions(this, options); if(promptPosition) options.promptPosition=promptPosition; options.showArrow = showArrow===true; methods._showPrompt(this, promptText, type, false, options); }, /** * Closes all error prompts on the page */ hidePrompt: function() { var promptClass = "."+ $(this).attr("id").replace(":","_") + "formError" $(promptClass).fadeTo("fast", 0.3, function() { $(this).remove(); }); }, /** * Closes form error prompts, CAN be invidual */ hide: function() { if($(this).is("form")){ var closingtag = "parentForm"+$(this).attr('id'); }else{ var closingtag = $(this).attr('id') +"formError" } $('.'+closingtag).fadeTo("fast", 0.3, function() { $(this).remove(); }); }, /** * Closes all error prompts on the page */ hideAll: function() { $('.formError').fadeTo("fast", 0.3, function() { $(this).remove(); }); }, /** * Typically called when user exists a field using tab or a mouse click, triggers a field * validation */ _onFieldEvent: function() { var field = $(this); var form = field.closest('form'); var options = form.data('jqv'); // validate the current field methods._validateField(field, options); }, /** * Called when the form is submited, shows prompts accordingly * * @param {jqObject} * form * @return false if form submission needs to be cancelled */ _onSubmitEvent: function() { var form = $(this); // validate each field (- skip field ajax validation, no necessary since we will perform an ajax form validation) var r=methods._validateFields(form, true); var options = form.data('jqv'); // validate the form using AJAX if (r && options.ajaxFormValidation) { methods._validateFormWithAjax(form, options); return false; } if(options.onValidationComplete) { options.onValidationComplete(form, r); return false; } return r; }, /** * Return true if the ajax field validations passed so far * @param {Object} options * @return true, is all ajax validation passed so far (remember ajax is async) */ _checkAjaxStatus: function(options) { var status = true; $.each(options.ajaxValidCache, function(key, value) { if (value === false) { status = false; // break the each return false; } }); return status; }, /** * Validates form fields, shows prompts accordingly * * @param {jqObject} * form * @param {skipAjaxFieldValidation} * boolean - when set to true, ajax field validation is skipped, typically used when the submit button is clicked * * @return true if form is valid, false if not, undefined if ajax form validation is done */ _validateFields: function(form, skipAjaxFieldValidation) { var options = form.data('jqv'); // this variable is set to true if an error is found var errorFound = false; // first, evaluate status of non ajax fields form.find('[class*=validate]').not(':hidden').each( function() { var field = $(this); // fields being valiated though ajax are marked with 'ajaxed', // skip them if (!field.hasClass("ajaxed")) errorFound |= methods._validateField(field, options, skipAjaxFieldValidation); }); // second, check to see if all ajax calls completed ok errorFound |= !methods._checkAjaxStatus(options); // thrird, check status and scroll the container accordingly if (errorFound) { if (options.scroll) { // get the position of the first error, there should be at least one, no need to check this //var destination = form.find(".formError:not('.greenPopup'):first").offset().top; // look for the visually top prompt var destination = Number.MAX_VALUE; var lst = $(".formError:not('.greenPopup')"); for (var i = 0; i < lst.length; i++) { var d = $(lst[i]).offset().top; if (d < destination) destination = d; } if (!options.isOverflown) $("html:not(:animated),body:not(:animated)").animate({ scrollTop: destination }, 1100); else { var overflowDIV = $(options.overflownDIV); var scrollContainerScroll = overflowDIV.scrollTop(); var scrollContainerPos = -parseInt(overflowDIV.offset().top); destination += scrollContainerScroll + scrollContainerPos - 5; var scrollContainer = $(options.overflownDIV + ":not(:animated)"); scrollContainer.animate({ scrollTop: destination }, 1100); } } return false; } return true; }, /** * This method is called to perform an ajax form validation. * During this process all the (field, value) pairs are sent to the server which returns a list of invalid fields or true * * @param {jqObject} form * @param {Map} options */ _validateFormWithAjax: function(form, options) { var data = form.serialize(); $.ajax({ type: "GET", url: form.attr("action"), cache: false, dataType: "json", data: data, form: form, methods: methods, options: options, beforeSend: function() { return options.onBeforeAjaxFormValidation(form, options); }, error: function(data, transport) { methods._ajaxError(data, transport); }, success: function(json) { if (json !== true) { // getting to this case doesn't necessary means that the form is invalid // the server may return green or closing prompt actions // this flag helps figuring it out var errorInForm=false; for (var i = 0; i < json.length; i++) { var value = json[i]; var errorFieldId = value[0]; var errorField = $($("#" + errorFieldId)[0]); // make sure we found the element if (errorField.length == 1) { // promptText or selector var msg = value[2]; if (value[1] === true) { if (msg == "") // if for some reason, status==true and error="", just close the prompt methods._closePrompt(errorField); else { // the field is valid, but we are displaying a green prompt if (options.allrules[msg]) { var txt = options.allrules[msg].alertTextOk; if (txt) msg = txt; } methods._showPrompt(errorField, msg, "pass", false, options); } } else { // the field is invalid, show the red error prompt errorInForm|=true; if (options.allrules[msg]) { var txt = options.allrules[msg].alertText; if (txt) msg = txt; } methods._showPrompt(errorField, msg, "", false, options); } } } options.onAjaxFormComplete(!errorInForm, form, json, options); } else options.onAjaxFormComplete(true, form, "", options); } }); }, /** * Validates field, shows prompts accordingly * * @param {jqObject} * field * @param {Array[String]} * field's validation rules * @param {Map} * user options * @return true if field is valid */ _validateField: function(field, options, skipAjaxFieldValidation) { if (!field.attr("id")) $.error("jQueryValidate: an ID attribute is required for this field: " + field.attr("name") + " class:" + field.attr("class")); var rulesParsing = field.attr('class'); var getRules = /validate\[(.*)\]/.exec(rulesParsing); if (getRules === null) return false; var str = getRules[1]; var rules = str.split(/\[|,|\]/); // true if we ran the ajax validation, tells the logic to stop messing with prompts var isAjaxValidator = false; var fieldName = field.attr("name"); var promptText = ""; var required = false; options.isError = false; options.showArrow = true; optional = false; for (var i = 0; i < rules.length; i++) { var errorMsg = undefined; switch (rules[i]) { case "optional": optional = true; break; case "required": required = true; errorMsg = methods._required(field, rules, i, options); break; case "custom": errorMsg = methods._customRegex(field, rules, i, options); break; case "ajax": if(skipAjaxFieldValidation===false) { // ajax has its own prompts handling technique methods._ajax(field, rules, i, options); isAjaxValidator = true; } break; case "minSize": errorMsg = methods._minSize(field, rules, i, options); break; case "maxSize": errorMsg = methods._maxSize(field, rules, i, options); break; case "min": errorMsg = methods._min(field, rules, i, options); break; case "max": errorMsg = methods._max(field, rules, i, options); break; case "past": errorMsg = methods._past(field, rules, i, options); break; case "future": errorMsg = methods._future(field, rules, i, options); break; case "maxCheckbox": errorMsg = methods._maxCheckbox(field, rules, i, options); field = $($("input[name='" + fieldName + "']")); break; case "minCheckbox": errorMsg = methods._minCheckbox(field, rules, i, options); field = $($("input[name='" + fieldName + "']")); break; case "equals": errorMsg = methods._equals(field, rules, i, options); break; case "funcCall": errorMsg = methods._funcCall(field, rules, i, options); break; default: //$.error("jQueryValidator rule not found"+rules[i]); } if (errorMsg !== undefined) { promptText += errorMsg + "<br/>"; options.isError = true; } } // If the rules required is not added, an empty field is not validated if(!required && !optional ){ if(field.val() == "") options.isError = false; } // Hack for radio/checkbox group button, the validation go into the // first radio/checkbox of the group var fieldType = field.attr("type"); if ((fieldType == "radio" || fieldType == "checkbox") && $("input[name='" + fieldName + "']").size() > 1) { field = $($("input[name='" + fieldName + "'][type!=hidden]:first")); options.showArrow = false; } if (!isAjaxValidator) { if (options.isError) methods._showPrompt(field, promptText, "", false, options); else methods._closePrompt(field); } return options.isError; }, /** * Required validation * * @param {jqObject} field * @param {Array[String]} rules * @param {int} i rules index * @param {Map} * user options * @return an error string if validation failed */ _required: function(field, rules, i, options) { switch (field.attr("type")) { case "text": case "password": case "textarea": case "file": default: if (!field.val()) return options.allrules[rules[i]].alertText; break; case "radio": case "checkbox": var name = field.attr("name"); if ($("input[name='" + name + "']:checked").size() === 0) { if ($("input[name='" + name + "']").size() === 1) return options.allrules[rules[i]].alertTextCheckboxe; else return options.allrules[rules[i]].alertTextCheckboxMultiple; } break; // required for <select> case "select-one": // added by paul@kinetek.net for select boxes, Thank you if (!field.val()) return options.allrules[rules[i]].alertText; break; case "select-multiple": // added by paul@kinetek.net for select boxes, Thank you if (!field.find("option:selected").val()) return options.allrules[rules[i]].alertText; break; } }, /** * Validate Regex rules * * @param {jqObject} field * @param {Array[String]} rules * @param {int} i rules index * @param {Map} * user options * @return an error string if validation failed */ _customRegex: function(field, rules, i, options) { var customRule = rules[i + 1]; var rule = options.allrules[customRule]; if(rule===undefined) { alert("jqv:custom rule not found "+customRule); return; } var ex=rule.regex; if(ex===undefined) { alert("jqv:custom regex not found "+customRule); return; } var pattern = new RegExp(ex); if (!pattern.test(field.attr('value'))) return options.allrules[customRule].alertText; }, /** * Validate custom function outside of the engine scope * * @param {jqObject} field * @param {Array[String]} rules * @param {int} i rules index * @param {Map} * user options * @return an error string if validation failed */ _funcCall: function(field, rules, i, options) { var functionName = rules[i + 1]; var fn = window[functionName]; if (typeof(fn) === 'function') return fn(field, rules, i, options); }, /** * Field match * * @param {jqObject} field * @param {Array[String]} rules * @param {int} i rules index * @param {Map} * user options * @return an error string if validation failed */ _equals: function(field, rules, i, options) { var equalsField = rules[i + 1]; if (field.attr('value') != $("#" + equalsField).attr('value')) return options.allrules.equals.alertText; }, /** * Check the maximum size (in characters) * * @param {jqObject} field * @param {Array[String]} rules * @param {int} i rules index * @param {Map} * user options * @return an error string if validation failed */ _maxSize: function(field, rules, i, options) { var max = rules[i + 1]; var len = field.attr('value').length; if (len > max) { var rule = options.allrules.maxSize; return rule.alertText + max + rule.alertText2; } }, /** * Check the minimum size (in characters) * * @param {jqObject} field * @param {Array[String]} rules * @param {int} i rules index * @param {Map} * user options * @return an error string if validation failed */ _minSize: function(field, rules, i, options) { var min = rules[i + 1]; var len = field.attr('value').length; if (len < min) { var rule = options.allrules.minSize; return rule.alertText + min + rule.alertText2; } }, /** * Check number minimum value * * @param {jqObject} field * @param {Array[String]} rules * @param {int} i rules index * @param {Map} * user options * @return an error string if validation failed */ _min: function(field, rules, i, options) { var min = parseFloat(rules[i + 1]); var len = parseFloat(field.attr('value')); if (len < min) { var rule = options.allrules.min; if (rule.alertText2) return rule.alertText + min + rule.alertText2; return rule.alertText + min; } }, /** * Check number maximum value * * @param {jqObject} field * @param {Array[String]} rules * @param {int} i rules index * @param {Map} * user options * @return an error string if validation failed */ _max: function(field, rules, i, options) { var max = parseFloat(rules[i + 1]); var len = parseFloat(field.attr('value')); if (len >max ) { var rule = options.allrules.max; if (rule.alertText2) return rule.alertText + max + rule.alertText2; //orefalo: to review, also do the translations return rule.alertText + max; } }, /** * Checks date is in the past * * @param {jqObject} field * @param {Array[String]} rules * @param {int} i rules index * @param {Map} * user options * @return an error string if validation failed */ _past: function(field, rules, i, options) { var p=rules[i + 1]; var pdate = (p.toLowerCase() == "now")? new Date():methods._parseDate(p); var vdate = methods._parseDate(field.attr('value')); if (vdate > pdate ) { var rule = options.allrules.past; if (rule.alertText2) return rule.alertText + methods._dateToString(pdate) + rule.alertText2; return rule.alertText + methods._dateToString(pdate); } }, /** * Checks date is in the past * * @param {jqObject} field * @param {Array[String]} rules * @param {int} i rules index * @param {Map} * user options * @return an error string if validation failed */ _future: function(field, rules, i, options) { var p=rules[i + 1]; var pdate = (p.toLowerCase() == "now")? new Date():methods._parseDate(p); var vdate = methods._parseDate(field.attr('value')); if (vdate < pdate ) { var rule = options.allrules.future; if (rule.alertText2) return rule.alertText + methods._dateToString(pdate) + rule.alertText2; return rule.alertText + methods._dateToString(pdate); } }, /** * Max number of checkbox selected * * @param {jqObject} field * @param {Array[String]} rules * @param {int} i rules index * @param {Map} * user options * @return an error string if validation failed */ _maxCheckbox: function(field, rules, i, options) { var nbCheck = rules[i + 1]; var groupname = field.attr("name"); var groupSize = $("input[name='" + groupname + "']:checked").size(); if (groupSize > nbCheck) { options.showArrow = false; return options.allrules.maxCheckbox.alertText; } }, /** * Min number of checkbox selected * * @param {jqObject} field * @param {Array[String]} rules * @param {int} i rules index * @param {Map} * user options * @return an error string if validation failed */ _minCheckbox: function(field, rules, i, options) { var nbCheck = rules[i + 1]; var groupname = field.attr("name"); var groupSize = $("input[name='" + groupname + "']:checked").size(); if (groupSize < nbCheck) { options.showArrow = false; return options.allrules.minCheckbox.alertText + " " + nbCheck + " " + options.allrules.minCheckbox.alertText2; } }, /** * Ajax field validation * * @param {jqObject} field * @param {Array[String]} rules * @param {int} i rules index * @param {Map} * user options * @return nothing! the ajax validator handles the prompts itself */ _ajax: function(field, rules, i, options) { var errorSelector = rules[i + 1]; var rule = options.allrules[errorSelector]; var extraData = rule.extraData; if (!extraData) extraData = ""; if (!options.isError) { $.ajax({ type: "GET", url: rule.url, cache: false, dataType: "json", data: "fieldId=" + field.attr("id") + "&fieldValue=" + field.attr("value") + "&extraData=" + extraData, field: field, rule: rule, methods: methods, options: options, beforeSend: function() { // build the loading prompt var loadingText = rule.alertTextLoad; if (loadingText) methods._showPrompt(field, loadingText, "load", true, options); }, error: function(data, transport) { methods._ajaxError(data, transport); }, success: function(json) { // asynchronously called on success, data is the json answer from the server var errorFieldId = json[0]; var errorField = $($("#" + errorFieldId)[0]); // make sure we found the element if (errorField.length == 1) { var status = json[1]; if (status === false) { // Houston we got a problem options.ajaxValidCache[errorFieldId] = false; options.isError = true; var promptText = rule.alertText; methods._showPrompt(errorField, promptText, "", true, options); } else { if (options.ajaxValidCache[errorFieldId] !== undefined) options.ajaxValidCache[errorFieldId] = true; // see if we should display a green prompt var alertTextOk = rule.alertTextOk; if (alertTextOk) methods._showPrompt(errorField, alertTextOk, "pass", true, options); else methods._closePrompt(errorField); } } } }); } }, /** * Common method to handle ajax errors * * @param {Object} data * @param {Object} transport */ _ajaxError: function(data, transport) { if(data.status === 0 && transport === null) alert("The page is not served from a server! ajax call failed"); else if(console) console.log("Ajax error: " + data.status + " " + transport); }, /** * date -> string * * @param {Object} date */ _dateToString: function(date) { return date.getFullYear()+"-"+(date.getMonth()+1)+"-"+date.getDate(); }, /** * Parses an ISO date * @param {String} d */ _parseDate: function(d) { var dateParts = d.split("-"); if(dateParts!==d) dateParts = d.split("/"); return new Date(dateParts[0], (dateParts[1] - 1) ,dateParts[2]); }, /** * Builds or updates a prompt with the given information * * @param {jqObject} field * @param {String} promptText html text to display type * @param {String} type the type of bubble: 'pass' (green), 'load' (black) anything else (red) * @param {boolean} ajaxed - use to mark fields than being validated with ajax * @param {Map} options user options */ _showPrompt: function(field, promptText, type, ajaxed, options) { var prompt = methods._getPrompt(field); if (prompt) methods._updatePrompt(field, prompt, promptText, type, ajaxed, options); else methods._buildPrompt(field, promptText, type, ajaxed, options); }, /** * Builds and shades a prompt for the given field. * * @param {jqObject} field * @param {String} promptText html text to display type * @param {String} type the type of bubble: 'pass' (green), 'load' (black) anything else (red) * @param {boolean} ajaxed - use to mark fields than being validated with ajax * @param {Map} options user options */ _buildPrompt: function(field, promptText, type, ajaxed, options) { // create the prompt var prompt = $('<div>'); prompt.addClass(field.attr("id").replace(":","_") + "formError"); // add a class name to identify the parent form of the prompt if(field.is(":input")) prompt.addClass("parentForm"+field.parents('form').attr("id").replace(":","_")); prompt.addClass("formError"); switch (type) { case "pass": prompt.addClass("greenPopup"); break; case "load": prompt.addClass("blackPopup"); } if (ajaxed) prompt.addClass("ajaxed"); // create the prompt content var promptContent = $('<div>').addClass("formErrorContent").html(promptText).appendTo(prompt); // create the css arrow pointing at the field // note that there is no triangle on max-checkbox and radio if (options.showArrow) { var arrow = $('<div>').addClass("formErrorArrow"); switch (options.promptPosition) { case "bottomLeft": case "bottomRight": prompt.find(".formErrorContent").before(arrow); arrow.addClass("formErrorArrowBottom").html('<div class="line1"><!-- --></div><div class="line2"><!-- --></div><div class="line3"><!-- --></div><div class="line4"><!-- --></div><div class="line5"><!-- --></div><div class="line6"><!-- --></div><div class="line7"><!-- --></div><div class="line8"><!-- --></div><div class="line9"><!-- --></div><div class="line10"><!-- --></div>'); break; case "topLeft": case "topRight": arrow.html('<div class="line10"><!-- --></div><div class="line9"><!-- --></div><div class="line8"><!-- --></div><div class="line7"><!-- --></div><div class="line6"><!-- --></div><div class="line5"><!-- --></div><div class="line4"><!-- --></div><div class="line3"><!-- --></div><div class="line2"><!-- --></div><div class="line1"><!-- --></div>'); prompt.append(arrow); break; } } //Cedric: Needed if a container is in position:relative // insert prompt in the form or in the overflown container? if (options.isOverflown) field.before(prompt); else $("body").append(prompt); var pos = methods._calculatePosition(field, prompt, options); prompt.css({ "top": pos.callerTopPosition, "left": pos.callerleftPosition, "marginTop": pos.marginTopSize, "opacity": 0 }); return prompt.animate({ "opacity": 0.87 }); }, /** * Updates the prompt text field - the field for which the prompt * @param {jqObject} field * @param {String} promptText html text to display type * @param {String} type the type of bubble: 'pass' (green), 'load' (black) anything else (red) * @param {boolean} ajaxed - use to mark fields than being validated with ajax * @param {Map} options user options */ _updatePrompt: function(field, prompt, promptText, type, ajaxed, options) { if (prompt) { if (type == "pass") prompt.addClass("greenPopup"); else prompt.removeClass("greenPopup"); if (type == "load") prompt.addClass("blackPopup"); else prompt.removeClass("blackPopup"); if (ajaxed) prompt.addClass("ajaxed"); else prompt.removeClass("ajaxed"); prompt.find(".formErrorContent").html(promptText); var pos = methods._calculatePosition(field, prompt, options); prompt.animate({ "top": pos.callerTopPosition, "marginTop": pos.marginTopSize }); } }, /** * Closes the prompt associated with the given field * * @param {jqObject} * field */ _closePrompt: function(field) { var prompt = methods._getPrompt(field); if (prompt) prompt.fadeTo("fast", 0, function() { prompt.remove(); }); }, closePrompt: function(field) { return methods._closePrompt(field); }, /** * Returns the error prompt matching the field if any * * @param {jqObject} * field * @return undefined or the error prompt (jqObject) */ _getPrompt: function(field) { var className = "." + field.attr("id").replace(":","_") + "formError"; var match = $(className)[0]; if (match) return $(match); }, /** * Calculates prompt position * * @param {jqObject} * field * @param {jqObject} * the prompt * @param {Map} * options * @return positions */ _calculatePosition: function(field, promptElmt, options) { var promptTopPosition, promptleftPosition, marginTopSize; var fieldWidth = field.width(); var promptHeight = promptElmt.height(); var overflow = options.isOverflown; if (overflow) { // is the form contained in an overflown container? promptTopPosition = promptleftPosition = 0; // compensation for the arrow marginTopSize = -promptHeight; } else { var offset = field.offset(); promptTopPosition = offset.top; promptleftPosition = offset.left; marginTopSize = 0; } switch (options.promptPosition) { default: case "topRight": if (overflow) // Is the form contained in an overflown container? promptleftPosition += fieldWidth - 30; else { promptleftPosition += fieldWidth - 30; promptTopPosition += -promptHeight; } break; case "topLeft": promptTopPosition += -promptHeight - 10; break; case "centerRight": promptleftPosition += fieldWidth + 13; break; case "bottomLeft": promptTopPosition = promptTopPosition + field.height() + 15; break; case "bottomRight": promptleftPosition += fieldWidth - 30; promptTopPosition += field.height() + 5; } return { "callerTopPosition": promptTopPosition + "px", "callerleftPosition": promptleftPosition + "px", "marginTopSize": marginTopSize + "px" }; }, /** * Saves the user options and variables in the form.data * * @param {jqObject} * form - the form where the user option should be saved * @param {Map} * options - the user options * @return the user options (extended from the defaults) */ _saveOptions: function(form, options) { // is there a language localisation ? if ($.validationEngineLanguage) var allRules = $.validationEngineLanguage.allRules; else $.error("jQuery.validationEngine rules are not loaded, plz add localization files to the page"); var userOptions = $.extend({ // Name of the event triggering field validation validationEventTrigger: "blur", // Automatically scroll viewport to the first error scroll: true, // Opening box position, possible locations are: topLeft, // topRight, bottomLeft, centerRight, bottomRight promptPosition: "topRight", bindMethod:"bind", // if set to true, the form data is sent asynchronously via ajax to the form.action url (get) ajaxFormValidation: false, // Ajax form validation callback method: boolean onComplete(form, status, errors, options) // retuns false if the form.submit event needs to be canceled. onAjaxFormComplete: $.noop, // called right before the ajax call, may return false to cancel onBeforeAjaxFormValidation: $.noop, // Stops form from submitting and execute function assiciated with it onValidationComplete: false, // Used when the form is displayed within a scrolling DIV isOverflown: false, overflownDIV: "", // --- Internals DO NOT TOUCH or OVERLOAD --- // validation rules and i18 allrules: allRules, // true when form and fields are binded binded: false, // set to true, when the prompt arrow needs to be displayed showArrow: true, // did one of the validation fail ? kept global to stop further ajax validations isError: false, // Caches field validation status, typically only bad status are created. // the array is used during ajax form validation to detect issues early and prevent an expensive submit ajaxValidCache: {} }, options); form.data('jqv', userOptions); return userOptions; } }; /** * Plugin entry point. * You may pass an action as a parameter or a list of options. * if none, the init and attach methods are being called. * Remember: if you pass options, the attached method is NOT called automatically * * @param {String} * method (optional) action */ $.fn.validationEngine = function(method) { var form = $(this); if(!form[0]) return false; // stop here if the form does not exist if (typeof(method) === 'string' && method.charAt(0) != '_' && methods[method]) { // make sure init is called once if(method != "showPrompt" && method != "hidePrompt" && method != "hide" && method != "hideAll") methods.init.apply(form); return methods[method].apply(form, Array.prototype.slice.call(arguments, 1)); } else if (typeof method === 'object' || !method) { // default constructor with or without arguments methods.init.apply(form, arguments); return methods.attach.apply(form); } else { $.error('Method ' + method + ' does not exist in jQuery.validationEngine'); } }; })(jQuery);
JavaScript
var anwajax = { load:function(url, id_class) { //load menu chinh $("#iconload").css('display','block'); $(id_class).load(url); $("#iconload").css('display','none'); }, category:function(links, id, li) { // load cac the loai nhac $("#iconload").css('display','block'); var url = site + links ; $('#'+id).load(url); $("#iconload").css('display','none'); // set selected $(".category ul li").removeClass('selected') ; $("#"+li).addClass("selected") ; }, banner:function(links, id) { var url = site + links ; $('#'+id).load(url); }, detail_events:function(links, id) { var url = site + links ; $.post(links,{id:id},function(data) { $('.detail_events').prepend(data); },'html'); } } /** * @method convert link * * @param objTagA * @param div * @return */ function convertLinkCodeAjax(objTagA, div) { var url = objTagA.href; objTagA.href = "javascript:void(0)"; var browser = navigator.appName; if (browser == "Microsoft Internet Explorer") { objTagA.onclick = function() { $('#' + div).load(url + "/" ); }; } else objTagA.setAttribute("onclick", "$('#" + div + "').load('" + url + "/');"); } function processPageBarCodeAjax(divPageBar, divAjax) { var common_page_bar = document.getElementById(divPageBar); var tagAs = common_page_bar.getElementsByTagName("A"); if (tagAs) { for ( var i = 0; i < tagAs.length; i++) { convertLinkCodeAjax(tagAs[i], divAjax); } } } function set_wave_music(catid) { $('div.catmusic div').html('') ; $('#catid' + catid).html('<img src="'+ site +'templates/images/songnhac.gif" height="25px">'); } function trit(a) { console.log(a) ; }
JavaScript
(function($){ $.fn.idTabs = function() { //Setup Tabs var ul = $('ul', this); //Save scope var self = this; var list = $('li', ul).bind('click', function() { var elm = $(this); // we set selected_section to keep active tab opened after form submit // we do it for all forms to fix settings_dev situation: forms under tabs if ($(self).hasClass('cm-track')) { $('input[name=selected_section]').val(this.id); } if (elm.hasClass('cm-js') == false) { return true; } /*if (hndl[$(ul).attr('id')]) { if (hndl[$(ul).attr('id')](elm.attr('id')) == false) { return false; } }*/ var id = '#content_' + this.id; var aList = []; //save tabs var idList = []; //save possible elements $('li', ul).each(function() { if(this.id) { aList[aList.length] = this; idList[idList.length] = '#content_' + this.id; } }); //Clear tabs, and hide all for (i in aList) { $(aList[i]).removeClass('cm-active'); } for (i in idList) { $(idList[i]).hide(); } //Select clicked tab and show content elm.addClass('cm-active'); // Switch buttons block only if: // 1. Current tab is in form and this form has cm-toggle-button class on buttons block or current tab does not belong to any form // 2. Current tab lays on is first-level tab var id_obj = $(id); if (($('.cm-toggle-button', id_obj.parents('form')).length > 0 || id_obj.parents('form').length == 0) && id_obj.parents('.cm-tabs-content').length == 1) { if (id_obj.hasClass('cm-hide-save-button')) { $('.cm-toggle-button').hide(); } else { $('.cm-toggle-button').show(); } } // Create tab content if it is not exist if (elm.hasClass('cm-ajax') && id_obj.length == 0) { $(self).after('<div id="' + id.substr(1) + '"></div>'); id_obj = $(id); jQuery.ajaxRequest($('a', elm).attr('href'), {result_ids: id.substr(1), callback: [id_obj, 'initTab']}); return false; } else { id_obj.initTab(); if (typeof(disable_ajax_preload) == 'undefined' || !disable_ajax_preload) { //jQuery.loadAjaxLinks($('a.cm-ajax-update', id_obj)); } } return false; //Option for changing url }); //Select default tab var test; if ((test = list.filter('.cm-active')).length) { test.click(); //Select tab with class 'cm-active' } else { list.filter(':first').click(); //Select first tab } $('li.cm-ajax.cm-js').not('.cm-active').each(function(){ var self = $(this); if (!self.data('passed') && $('a', self).attr('href')) { self.data('passed', true); var id = 'content_' + this.id; self.parents('.cm-j-tabs').eq(0).next().prepend('<div id="' + id + '"></div>'); $('#' + id).hide(); jQuery.ajaxRequest($('a', self).attr('href'), {result_ids: id, hidden: true, repeat_on_error: true}); } }); return this; //Chainable }; $(function(){ $(".cm-j-tabs").each(function(){ $(this).idTabs(); }); }); })(jQuery); jQuery.fn.extend({ initTab: function () { this.show(); control_buttons_container = $('.buttons-bg'); if (control_buttons_container.length) { control_buttons_floating = $('.cm-buttons-floating', control_buttons_container); if (control_buttons_container.length != control_buttons_floating.length) { control_buttons_container.each(function () { if (!$('.cm-buttons-floating', this).length) { if ($('.cm-popup-box', this).length) { $('.cm-popup-box', this).each(function () { if ($('iframe', this).length) { $(this).appendTo(document.body); } else { $(this).appendTo($(this).parents('.buttons-bg:first').parent()); } }); } $(this).wrapInner('<div class="cm-buttons-placeholder"></div>'); $(this).append('<div class="cm-buttons-floating hidden"></div>'); } }); control_buttons_container = $('.buttons-bg'); control_buttons_floating = $('.cm-buttons-floating', control_buttons_container); } jQuery.buttonsPlaceholderToggle(); } } });
JavaScript
/*! * jQuery UI Widget 1.8.5 * * Copyright 2010, AUTHORS.txt (http://jqueryui.com/about) * Dual licensed under the MIT or GPL Version 2 licenses. * http://jquery.org/license * * http://docs.jquery.com/UI/Widget */ (function( $, undefined ) { // jQuery 1.4+ if ( $.cleanData ) { var _cleanData = $.cleanData; $.cleanData = function( elems ) { for ( var i = 0, elem; (elem = elems[i]) != null; i++ ) { $( elem ).triggerHandler( "remove" ); } _cleanData( elems ); }; } else { var _remove = $.fn.remove; $.fn.remove = function( selector, keepData ) { return this.each(function() { if ( !keepData ) { if ( !selector || $.filter( selector, [ this ] ).length ) { $( "*", this ).add( [ this ] ).each(function() { $( this ).triggerHandler( "remove" ); }); } } return _remove.call( $(this), selector, keepData ); }); }; } $.widget = function( name, base, prototype ) { var namespace = name.split( "." )[ 0 ], fullName; name = name.split( "." )[ 1 ]; fullName = namespace + "-" + name; if ( !prototype ) { prototype = base; base = $.Widget; } // create selector for plugin $.expr[ ":" ][ fullName ] = function( elem ) { return !!$.data( elem, name ); }; $[ namespace ] = $[ namespace ] || {}; $[ namespace ][ name ] = function( options, element ) { // allow instantiation without initializing for simple inheritance if ( arguments.length ) { this._createWidget( options, element ); } }; var basePrototype = new base(); // we need to make the options hash a property directly on the new instance // otherwise we'll modify the options hash on the prototype that we're // inheriting from // $.each( basePrototype, function( key, val ) { // if ( $.isPlainObject(val) ) { // basePrototype[ key ] = $.extend( {}, val ); // } // }); basePrototype.options = $.extend( true, {}, basePrototype.options ); $[ namespace ][ name ].prototype = $.extend( true, basePrototype, { namespace: namespace, widgetName: name, widgetEventPrefix: $[ namespace ][ name ].prototype.widgetEventPrefix || name, widgetBaseClass: fullName }, prototype ); $.widget.bridge( name, $[ namespace ][ name ] ); }; $.widget.bridge = function( name, object ) { $.fn[ name ] = function( options ) { var isMethodCall = typeof options === "string", args = Array.prototype.slice.call( arguments, 1 ), returnValue = this; // allow multiple hashes to be passed on init options = !isMethodCall && args.length ? $.extend.apply( null, [ true, options ].concat(args) ) : options; // prevent calls to internal methods if ( isMethodCall && options.substring( 0, 1 ) === "_" ) { return returnValue; } if ( isMethodCall ) { this.each(function() { var instance = $.data( this, name ); if ( !instance ) { throw "cannot call methods on " + name + " prior to initialization; " + "attempted to call method '" + options + "'"; } if ( !$.isFunction( instance[options] ) ) { throw "no such method '" + options + "' for " + name + " widget instance"; } var methodValue = instance[ options ].apply( instance, args ); if ( methodValue !== instance && methodValue !== undefined ) { returnValue = methodValue; return false; } }); } else { this.each(function() { var instance = $.data( this, name ); if ( instance ) { instance.option( options || {} )._init(); } else { $.data( this, name, new object( options, this ) ); } }); } return returnValue; }; }; $.Widget = function( options, element ) { // allow instantiation without initializing for simple inheritance if ( arguments.length ) { this._createWidget( options, element ); } }; $.Widget.prototype = { widgetName: "widget", widgetEventPrefix: "", options: { disabled: false }, _createWidget: function( options, element ) { // $.widget.bridge stores the plugin instance, but we do it anyway // so that it's stored even before the _create function runs $.data( element, this.widgetName, this ); this.element = $( element ); this.options = $.extend( true, {}, this.options, $.metadata && $.metadata.get( element )[ this.widgetName ], options ); var self = this; this.element.bind( "remove." + this.widgetName, function() { self.destroy(); }); this._create(); this._init(); }, _create: function() {}, _init: function() {}, destroy: function() { this.element .unbind( "." + this.widgetName ) .removeData( this.widgetName ); this.widget() .unbind( "." + this.widgetName ) .removeAttr( "aria-disabled" ) .removeClass( this.widgetBaseClass + "-disabled " + "ui-state-disabled" ); }, widget: function() { return this.element; }, option: function( key, value ) { var options = key, self = this; if ( arguments.length === 0 ) { // don't return a reference to the internal hash return $.extend( {}, self.options ); } if (typeof key === "string" ) { if ( value === undefined ) { return this.options[ key ]; } options = {}; options[ key ] = value; } $.each( options, function( key, value ) { self._setOption( key, value ); }); return self; }, _setOption: function( key, value ) { this.options[ key ] = value; if ( key === "disabled" ) { this.widget() [ value ? "addClass" : "removeClass"]( this.widgetBaseClass + "-disabled" + " " + "ui-state-disabled" ) .attr( "aria-disabled", value ); } return this; }, enable: function() { return this._setOption( "disabled", false ); }, disable: function() { return this._setOption( "disabled", true ); }, _trigger: function( type, event, data ) { var callback = this.options[ type ]; event = $.Event( event ); event.type = ( type === this.widgetEventPrefix ? type : this.widgetEventPrefix + type ).toLowerCase(); data = data || {}; // copy original event properties over to the new event // this would happen if we could call $.event.fix instead of $.Event // but we don't have a way to force an event to be fixed multiple times if ( event.originalEvent ) { for ( var i = $.event.props.length, prop; i; ) { prop = $.event.props[ --i ]; event[ prop ] = event.originalEvent[ prop ]; } } this.element.trigger( event, data ); return !( $.isFunction(callback) && callback.call( this.element[0], event, data ) === false || event.isDefaultPrevented() ); } }; })( jQuery );
JavaScript
// Ẩn. Hiển thị Menu trái function clickHide(type){ if (type == 1){ $('td.colum_left_lage').css('display','none'); $('td.colum_left_small').css('display','table-cell'); //nv_setCookie( 'colum_left_lage', '0', 86400000); } else { if (type == 2){ $('td.colum_left_small').css('display','none'); $('td.colum_left_lage').css('display','table-cell'); //nv_setCookie( 'colum_left_lage', '1', 86400000); } } } // show or hide menu function show_menu(){ var showmenu = ( nv_getCookie( 'colum_left_lage' ) ) ? ( nv_getCookie('colum_left_lage')) : '1'; if (showmenu == '1') { $('td.colum_left_small').hide(); $('td.colum_left_lage').show(); }else { $('td.colum_left_small').show(); $('td.colum_left_lage').hide(); } } // Submit button form $(document).ready(function() { $('#bt_del').bind('click', function() { $('#adminform').submit(); }); });
JavaScript
/* Copyright (c) 2003-2010, CKSource - Frederico Knabben. All rights reserved. For licensing, see LICENSE.html or http://ckeditor.com/license */ // Compressed version of core/ckeditor_base.js. See original for instructions. /*jsl:ignore*/ if(!window.CKEDITOR)window.CKEDITOR=(function(){var a={timestamp:'',version:'3.4',revision:'5825',_:{},status:'unloaded',basePath:(function(){var d=window.CKEDITOR_BASEPATH||'';if(!d){var e=document.getElementsByTagName('script');for(var f=0;f<e.length;f++){var g=e[f].src.match(/(^|.*[\\\/])ckeditor(?:_basic)?(?:_source)?.js(?:\?.*)?$/i);if(g){d=g[1];break;}}}if(d.indexOf('://')==-1)if(d.indexOf('/')===0)d=location.href.match(/^.*?:\/\/[^\/]*/)[0]+d;else d=location.href.match(/^[^\?]*\/(?:)/)[0]+d;return d;})(),getUrl:function(d){if(d.indexOf('://')==-1&&d.indexOf('/')!==0)d=this.basePath+d;if(this.timestamp&&d.charAt(d.length-1)!='/')d+=(d.indexOf('?')>=0?'&':'?')+('t=')+this.timestamp;return d;}},b=window.CKEDITOR_GETURL;if(b){var c=a.getUrl;a.getUrl=function(d){return b.call(a,d)||c.call(a,d);};}return a;})(); /*jsl:end*/ // Uncomment the following line to have a new timestamp generated for each // request, having clear cache load of the editor code. // CKEDITOR.timestamp = ( new Date() ).valueOf(); if ( CKEDITOR.loader ) CKEDITOR.loader.load( 'core/ckeditor' ); else { // Set the script name to be loaded by the loader. CKEDITOR._autoLoad = 'core/ckeditor'; // Include the loader script. document.write( '<script type="text/javascript" src="' + CKEDITOR.getUrl( '_source/core/loader.js' ) + '"></script>' ); }
JavaScript
/* Copyright (c) 2003-2010, CKSource - Frederico Knabben. All rights reserved. For licensing, see LICENSE.html or http://ckeditor.com/license */ /** * @fileOverview Defines the {@link CKEDITOR.lang} object, for the * Dutch language. */ /**#@+ @type String @example */ /** * Constains the dictionary of language entries. * @namespace */ CKEDITOR.lang['nl'] = { /** * The language reading direction. Possible values are "rtl" for * Right-To-Left languages (like Arabic) and "ltr" for Left-To-Right * languages (like English). * @default 'ltr' */ dir : 'ltr', /* * Screenreader titles. Please note that screenreaders are not always capable * of reading non-English words. So be careful while translating it. */ editorTitle : 'Tekstverwerker, %1, druk op ALT 0 voor hulp.', // ARIA descriptions. toolbar : 'Werkbalk', editor : 'Tekstverwerker', // Toolbar buttons without dialogs. source : 'Code', newPage : 'Nieuwe pagina', save : 'Opslaan', preview : 'Voorbeeld', cut : 'Knippen', copy : 'Kopiëren', paste : 'Plakken', print : 'Printen', underline : 'Onderstreept', bold : 'Vet', italic : 'Schuingedrukt', selectAll : 'Alles selecteren', removeFormat : 'Opmaak verwijderen', strike : 'Doorhalen', subscript : 'Subscript', superscript : 'Superscript', horizontalrule : 'Horizontale lijn invoegen', pagebreak : 'Pagina-einde invoegen', unlink : 'Link verwijderen', undo : 'Ongedaan maken', redo : 'Opnieuw uitvoeren', // Common messages and labels. common : { browseServer : 'Bladeren op server', url : 'URL', protocol : 'Protocol', upload : 'Upload', uploadSubmit : 'Naar server verzenden', image : 'Afbeelding', flash : 'Flash', form : 'Formulier', checkbox : 'Aanvinkvakje', radio : 'Selectievakje', textField : 'Tekstveld', textarea : 'Tekstvak', hiddenField : 'Verborgen veld', button : 'Knop', select : 'Selectieveld', imageButton : 'Afbeeldingsknop', notSet : '<niet ingevuld>', id : 'Kenmerk', name : 'Naam', langDir : 'Schrijfrichting', langDirLtr : 'Links naar rechts (LTR)', langDirRtl : 'Rechts naar links (RTL)', langCode : 'Taalcode', longDescr : 'Lange URL-omschrijving', cssClass : 'Stylesheet-klassen', advisoryTitle : 'Aanbevolen titel', cssStyle : 'Stijl', ok : 'OK', cancel : 'Annuleren', close : 'Sluiten', preview : 'Voorbeeld', generalTab : 'Algemeen', advancedTab : 'Geavanceerd', validateNumberFailed : 'Deze waarde is geen geldig getal.', confirmNewPage : 'Alle aangebrachte wijzigingen gaan verloren. Weet u zeker dat u een nieuwe pagina wilt openen?', confirmCancel : 'Enkele opties zijn gewijzigd. Weet u zeker dat u dit dialoogvenster wilt sluiten?', options : 'Opties', target : 'Doel', targetNew : 'Nieuw venster (_blank)', targetTop : 'Hele venster (_top)', targetSelf : 'Zelfde venster (_self)', targetParent : 'Origineel venster (_parent)', langDirLTR : 'Links naar rechts (LTR)', langDirRTL : 'Rechts naar links (RTL)', styles : 'Stijlen', cssClasses : 'Stylesheet klassen', // Put the voice-only part of the label in the span. unavailable : '%1<span class="cke_accessibility">, niet beschikbaar</span>' }, contextmenu : { options : 'Context menu opties' }, // Special char dialog. specialChar : { toolbar : 'Speciaal teken invoegen', title : 'Selecteer speciaal teken', options : 'Speciale tekens opties' }, // Link dialog. link : { toolbar : 'Link invoegen/wijzigen', other : '<ander>', menu : 'Link wijzigen', title : 'Link', info : 'Linkomschrijving', target : 'Doel', upload : 'Upload', advanced : 'Geavanceerd', type : 'Linktype', toUrl : 'URL', toAnchor : 'Interne link in pagina', toEmail : 'E-mail', targetFrame : '<frame>', targetPopup : '<popup window>', targetFrameName : 'Naam doelframe', targetPopupName : 'Naam popupvenster', popupFeatures : 'Instellingen popupvenster', popupResizable : 'Herschaalbaar', popupStatusBar : 'Statusbalk', popupLocationBar: 'Locatiemenu', popupToolbar : 'Menubalk', popupMenuBar : 'Menubalk', popupFullScreen : 'Volledig scherm (IE)', popupScrollBars : 'Schuifbalken', popupDependent : 'Afhankelijk (Netscape)', popupWidth : 'Breedte', popupLeft : 'Positie links', popupHeight : 'Hoogte', popupTop : 'Positie boven', id : 'Id', langDir : 'Schrijfrichting', langDirLTR : 'Links naar rechts (LTR)', langDirRTL : 'Rechts naar links (RTL)', acccessKey : 'Toegangstoets', name : 'Naam', langCode : 'Schrijfrichting', tabIndex : 'Tabvolgorde', advisoryTitle : 'Aanbevolen titel', advisoryContentType : 'Aanbevolen content-type', cssClasses : 'Stylesheet-klassen', charset : 'Karakterset van gelinkte bron', styles : 'Stijl', selectAnchor : 'Kies een interne link', anchorName : 'Op naam interne link', anchorId : 'Op kenmerk interne link', emailAddress : 'E-mailadres', emailSubject : 'Onderwerp bericht', emailBody : 'Inhoud bericht', noAnchors : '(Geen interne links in document gevonden)', noUrl : 'Geef de link van de URL', noEmail : 'Geef een e-mailadres' }, // Anchor dialog anchor : { toolbar : 'Interne link', menu : 'Eigenschappen interne link', title : 'Eigenschappen interne link', name : 'Naam interne link', errorName : 'Geef de naam van de interne link op' }, // List style dialog list: { numberedTitle : 'Eigenschappen genummerde lijst', bulletedTitle : 'Eigenschappen lijst met opsommingstekens', type : 'Type', start : 'Start', validateStartNumber :'Starnummer van de lijst moet een heel nummer zijn.', circle : 'Cirkel', disc : 'Schijf', square : 'Vierkant', none : 'Geen', notset : '<niet gezet>', armenian : 'Armeense numering', georgian : 'Greorgische numering (an, ban, gan, etc.)', lowerRoman : 'Romeins kleine letters (i, ii, iii, iv, v, etc.)', upperRoman : 'Romeins hoofdletters (I, II, III, IV, V, etc.)', lowerAlpha : 'Kleine letters (a, b, c, d, e, etc.)', upperAlpha : 'Hoofdletters (A, B, C, D, E, etc.)', lowerGreek : 'Grieks kleine letters (alpha, beta, gamma, etc.)', decimal : 'Cijfers (1, 2, 3, etc.)', decimalLeadingZero : 'Cijfers beginnen met nul (01, 02, 03, etc.)' }, // Find And Replace Dialog findAndReplace : { title : 'Zoeken en vervangen', find : 'Zoeken', replace : 'Vervangen', findWhat : 'Zoeken naar:', replaceWith : 'Vervangen met:', notFoundMsg : 'De opgegeven tekst is niet gevonden.', matchCase : 'Hoofdlettergevoelig', matchWord : 'Hele woord moet voorkomen', matchCyclic : 'Doorlopend zoeken', replaceAll : 'Alles vervangen', replaceSuccessMsg : '%1 resulaten vervangen.' }, // Table Dialog table : { toolbar : 'Tabel', title : 'Eigenschappen tabel', menu : 'Eigenschappen tabel', deleteTable : 'Tabel verwijderen', rows : 'Rijen', columns : 'Kolommen', border : 'Breedte rand', align : 'Uitlijning', alignLeft : 'Links', alignCenter : 'Centreren', alignRight : 'Rechts', width : 'Breedte', widthPx : 'pixels', widthPc : 'procent', widthUnit : 'eenheid breedte', height : 'Hoogte', cellSpace : 'Afstand tussen cellen', cellPad : 'Ruimte in de cel', caption : 'Naam', summary : 'Samenvatting', headers : 'Koppen', headersNone : 'Geen', headersColumn : 'Eerste kolom', headersRow : 'Eerste rij', headersBoth : 'Beide', invalidRows : 'Het aantal rijen moet een getal zijn groter dan 0.', invalidCols : 'Het aantal kolommen moet een getal zijn groter dan 0.', invalidBorder : 'De rand breedte moet een getal zijn.', invalidWidth : 'De tabel breedte moet een getal zijn.', invalidHeight : 'De tabel hoogte moet een getal zijn.', invalidCellSpacing : 'Afstand tussen cellen moet een getal zijn.', invalidCellPadding : 'Ruimte in de cel moet een getal zijn.', cell : { menu : 'Cel', insertBefore : 'Voeg cel in voor', insertAfter : 'Voeg cel in achter', deleteCell : 'Cellen verwijderen', merge : 'Cellen samenvoegen', mergeRight : 'Voeg samen naar rechts', mergeDown : 'Voeg samen naar beneden', splitHorizontal : 'Splits cellen horizontaal', splitVertical : 'Splits cellen verticaal', title : 'Cel eigenschappen', cellType : 'Cel type', rowSpan : 'Rijen samenvoegen', colSpan : 'Kolommen samenvoegen', wordWrap : 'Automatische terugloop', hAlign : 'Horizontale uitlijning', vAlign : 'Verticale uitlijning', alignTop : 'Boven', alignMiddle : 'Midden', alignBottom : 'Onder', alignBaseline : 'Basislijn', bgColor : 'Achtergrondkleur', borderColor : 'Kleur rand', data : 'Inhoud', header : 'Kop', yes : 'Ja', no : 'Nee', invalidWidth : 'De celbreedte moet een getal zijn.', invalidHeight : 'De celhoogte moet een getal zijn.', invalidRowSpan : 'Rijen samenvoegen moet een heel getal zijn.', invalidColSpan : 'Kolommen samenvoegen moet een heel getal zijn.', chooseColor : 'Kies' }, row : { menu : 'Rij', insertBefore : 'Voeg rij in voor', insertAfter : 'Voeg rij in achter', deleteRow : 'Rijen verwijderen' }, column : { menu : 'Kolom', insertBefore : 'Voeg kolom in voor', insertAfter : 'Voeg kolom in achter', deleteColumn : 'Kolommen verwijderen' } }, // Button Dialog. button : { title : 'Eigenschappen knop', text : 'Tekst (waarde)', type : 'Soort', typeBtn : 'Knop', typeSbm : 'Versturen', typeRst : 'Leegmaken' }, // Checkbox and Radio Button Dialogs. checkboxAndRadio : { checkboxTitle : 'Eigenschappen aanvinkvakje', radioTitle : 'Eigenschappen selectievakje', value : 'Waarde', selected : 'Geselecteerd' }, // Form Dialog. form : { title : 'Eigenschappen formulier', menu : 'Eigenschappen formulier', action : 'Actie', method : 'Methode', encoding : 'Codering' }, // Select Field Dialog. select : { title : 'Eigenschappen selectieveld', selectInfo : 'Informatie', opAvail : 'Beschikbare opties', value : 'Waarde', size : 'Grootte', lines : 'Regels', chkMulti : 'Gecombineerde selecties toestaan', opText : 'Tekst', opValue : 'Waarde', btnAdd : 'Toevoegen', btnModify : 'Wijzigen', btnUp : 'Omhoog', btnDown : 'Omlaag', btnSetValue : 'Als geselecteerde waarde instellen', btnDelete : 'Verwijderen' }, // Textarea Dialog. textarea : { title : 'Eigenschappen tekstvak', cols : 'Kolommen', rows : 'Rijen' }, // Text Field Dialog. textfield : { title : 'Eigenschappen tekstveld', name : 'Naam', value : 'Waarde', charWidth : 'Breedte (tekens)', maxChars : 'Maximum aantal tekens', type : 'Soort', typeText : 'Tekst', typePass : 'Wachtwoord' }, // Hidden Field Dialog. hidden : { title : 'Eigenschappen verborgen veld', name : 'Naam', value : 'Waarde' }, // Image Dialog. image : { title : 'Eigenschappen afbeelding', titleButton : 'Eigenschappen afbeeldingsknop', menu : 'Eigenschappen afbeelding', infoTab : 'Informatie afbeelding', btnUpload : 'Naar server verzenden', upload : 'Upload', alt : 'Alternatieve tekst', width : 'Breedte', height : 'Hoogte', lockRatio : 'Afmetingen vergrendelen', unlockRatio : 'Afmetingen ontgrendelen', resetSize : 'Afmetingen resetten', border : 'Rand', hSpace : 'HSpace', vSpace : 'VSpace', align : 'Uitlijning', alignLeft : 'Links', alignRight : 'Rechts', alertUrl : 'Geef de URL van de afbeelding', linkTab : 'Link', button2Img : 'Wilt u de geselecteerde afbeeldingsknop vervangen door een eenvoudige afbeelding?', img2Button : 'Wilt u de geselecteerde afbeelding vervangen door een afbeeldingsknop?', urlMissing : 'De URL naar de afbeelding ontbreekt.', validateWidth : 'Breedte moet een heel nummer zijn.', validateHeight : 'Hoogte moet een heel nummer zijn.', validateBorder : 'Rand moet een heel nummer zijn.', validateHSpace : 'HSpace moet een heel nummer zijn.', validateVSpace : 'VSpace moet een heel nummer zijn.' }, // Flash Dialog flash : { properties : 'Eigenschappen Flash', propertiesTab : 'Eigenschappen', title : 'Eigenschappen Flash', chkPlay : 'Automatisch afspelen', chkLoop : 'Herhalen', chkMenu : 'Flashmenu\'s inschakelen', chkFull : 'Schermvullend toestaan', scale : 'Schaal', scaleAll : 'Alles tonen', scaleNoBorder : 'Geen rand', scaleFit : 'Precies passend', access : 'Script toegang', accessAlways : 'Altijd', accessSameDomain: 'Zelfde domeinnaam', accessNever : 'Nooit', align : 'Uitlijning', alignLeft : 'Links', alignAbsBottom : 'Absoluut-onder', alignAbsMiddle : 'Absoluut-midden', alignBaseline : 'Basislijn', alignBottom : 'Beneden', alignMiddle : 'Midden', alignRight : 'Rechts', alignTextTop : 'Boven tekst', alignTop : 'Boven', quality : 'Kwaliteit', qualityBest : 'Beste', qualityHigh : 'Hoog', qualityAutoHigh : 'Automatisch hoog', qualityMedium : 'Gemiddeld', qualityAutoLow : 'Automatisch laag', qualityLow : 'Laag', windowModeWindow: 'Venster', windowModeOpaque: 'Ondoorzichtig', windowModeTransparent : 'Doorzichtig', windowMode : 'Venster modus', flashvars : 'Variabelen voor Flash', bgcolor : 'Achtergrondkleur', width : 'Breedte', height : 'Hoogte', hSpace : 'HSpace', vSpace : 'VSpace', validateSrc : 'Geef de link van de URL', validateWidth : 'De breedte moet een getal zijn.', validateHeight : 'De hoogte moet een getal zijn.', validateHSpace : 'De HSpace moet een getal zijn.', validateVSpace : 'De VSpace moet een getal zijn.' }, // Speller Pages Dialog spellCheck : { toolbar : 'Spellingscontrole', title : 'Spellingscontrole', notAvailable : 'Excuses, deze dienst is momenteel niet beschikbaar.', errorLoading : 'Er is een fout opgetreden bij het laden van de diesnt: %s.', notInDic : 'Niet in het woordenboek', changeTo : 'Wijzig in', btnIgnore : 'Negeren', btnIgnoreAll : 'Alles negeren', btnReplace : 'Vervangen', btnReplaceAll : 'Alles vervangen', btnUndo : 'Ongedaan maken', noSuggestions : '-Geen suggesties-', progress : 'Bezig met spellingscontrole...', noMispell : 'Klaar met spellingscontrole: geen fouten gevonden', noChanges : 'Klaar met spellingscontrole: geen woorden aangepast', oneChange : 'Klaar met spellingscontrole: één woord aangepast', manyChanges : 'Klaar met spellingscontrole: %1 woorden aangepast', ieSpellDownload : 'De spellingscontrole niet geïnstalleerd. Wilt u deze nu downloaden?' }, smiley : { toolbar : 'Smiley', title : 'Smiley invoegen', options : 'Smiley opties' }, elementsPath : { eleLabel : 'Elementenpad', eleTitle : '%1 element' }, numberedlist : 'Genummerde lijst', bulletedlist : 'Opsomming', indent : 'Inspringen vergroten', outdent : 'Inspringen verkleinen', justify : { left : 'Links uitlijnen', center : 'Centreren', right : 'Rechts uitlijnen', block : 'Uitvullen' }, blockquote : 'Citaatblok', clipboard : { title : 'Plakken', cutError : 'De beveiligingsinstelling van de browser verhinderen het automatisch knippen. Gebruik de sneltoets Ctrl/Cmd+X van het toetsenbord.', copyError : 'De beveiligingsinstelling van de browser verhinderen het automatisch kopiëren. Gebruik de sneltoets Ctrl/Cmd+C van het toetsenbord.', pasteMsg : 'Plak de tekst in het volgende vak gebruik makend van uw toetsenbord (<strong>Ctrl/Cmd+V</strong>) en klik op <strong>OK</strong>.', securityMsg : 'Door de beveiligingsinstellingen van uw browser is het niet mogelijk om direct vanuit het klembord in de editor te plakken. Middels opnieuw plakken in dit venster kunt u de tekst alsnog plakken in de editor.', pasteArea : 'Plakgebied' }, pastefromword : { confirmCleanup : 'De tekst die u plakte lijkt gekopieerd te zijn vanuit Word. Wilt u de tekst opschonen voordat deze geplakt wordt?', toolbar : 'Plakken als Word-gegevens', title : 'Plakken als Word-gegevens', error : 'Het was niet mogelijk om de geplakte tekst op te schonen door een interne fout' }, pasteText : { button : 'Plakken als platte tekst', title : 'Plakken als platte tekst' }, templates : { button : 'Sjablonen', title : 'Inhoud sjabonen', options : 'Template opties', insertOption : 'Vervang de huidige inhoud', selectPromptMsg : 'Selecteer het sjabloon dat in de editor geopend moet worden (de actuele inhoud gaat verloren):', emptyListMsg : '(Geen sjablonen gedefinieerd)' }, showBlocks : 'Toon blokken', stylesCombo : { label : 'Stijl', panelTitle : 'Opmaakstijlen', panelTitle1 : 'Blok stijlen', panelTitle2 : 'In-line stijlen', panelTitle3 : 'Object stijlen' }, format : { label : 'Opmaak', panelTitle : 'Opmaak', tag_p : 'Normaal', tag_pre : 'Met opmaak', tag_address : 'Adres', tag_h1 : 'Kop 1', tag_h2 : 'Kop 2', tag_h3 : 'Kop 3', tag_h4 : 'Kop 4', tag_h5 : 'Kop 5', tag_h6 : 'Kop 6', tag_div : 'Normaal (DIV)' }, div : { title : 'Div aanmaken', toolbar : 'Div aanmaken', cssClassInputLabel : 'Stylesheet klassen', styleSelectLabel : 'Stijl', IdInputLabel : 'Id', languageCodeInputLabel : ' Taalcode', inlineStyleInputLabel : 'Inline stijl', advisoryTitleInputLabel : 'informatieve titel', langDirLabel : 'Schrijfrichting', langDirLTRLabel : 'Links naar rechts (LTR)', langDirRTLLabel : 'Rechts naar links (RTL)', edit : 'Div wijzigen', remove : 'Div verwijderen' }, font : { label : 'Lettertype', voiceLabel : 'Lettertype', panelTitle : 'Lettertype' }, fontSize : { label : 'Lettergrootte', voiceLabel : 'Lettergrootte', panelTitle : 'Lettergrootte' }, colorButton : { textColorTitle : 'Tekstkleur', bgColorTitle : 'Achtergrondkleur', panelTitle : 'Kleuren', auto : 'Automatisch', more : 'Meer kleuren...' }, colors : { '000' : 'Zwart', '800000' : 'Kastanjebruin', '8B4513' : 'Chocoladebruin', '2F4F4F' : 'Donkerleigrijs', '008080' : 'Blauwgroen', '000080' : 'Marine', '4B0082' : 'Indigo', '696969' : 'Donkergrijs', 'B22222' : 'Baksteen', 'A52A2A' : 'Bruin', 'DAA520' : 'Donkergeel', '006400' : 'Donkergroen', '40E0D0' : 'Turquoise', '0000CD' : 'Middenblauw', '800080' : 'Paars', '808080' : 'Grijs', 'F00' : 'Rood', 'FF8C00' : 'Donkeroranje', 'FFD700' : 'Goud', '008000' : 'Groen', '0FF' : 'Cyaan', '00F' : 'Blauw', 'EE82EE' : 'Violet', 'A9A9A9' : 'Donkergrijs', 'FFA07A' : 'Lichtzalm', 'FFA500' : 'Oranje', 'FFFF00' : 'Geel', '00FF00' : 'Felgroen', 'AFEEEE' : 'Lichtturquoise', 'ADD8E6' : 'Lichtblauw', 'DDA0DD' : 'Pruim', 'D3D3D3' : 'Lichtgrijs', 'FFF0F5' : 'Linnen', 'FAEBD7' : 'Ivoor', 'FFFFE0' : 'Lichtgeel', 'F0FFF0' : 'Honingdauw', 'F0FFFF' : 'Azuur', 'F0F8FF' : 'Licht hemelsblauw', 'E6E6FA' : 'Lavendel', 'FFF' : 'Wit' }, scayt : { title : 'Controleer de spelling tijdens het typen', opera_title : 'Niet ondersteund door Opera', enable : 'SCAYT inschakelen', disable : 'SCAYT uitschakelen', about : 'Over SCAYT', toggle : 'SCAYT in/uitschakelen', options : 'Opties', langs : 'Talen', moreSuggestions : 'Meer suggesties', ignore : 'Negeren', ignoreAll : 'Alles negeren', addWord : 'Woord toevoegen', emptyDic : 'De naam van het woordenboek mag niet leeg zijn.', optionsTab : 'Opties', allCaps : 'Negeer woorden helemaal in hoofdletters', ignoreDomainNames : 'Negeer domeinnamen', mixedCase : 'Negeer woorden met hoofd- en kleine letters', mixedWithDigits : 'Negeer woorden met cijfers', languagesTab : 'Talen', dictionariesTab : 'Woordenboeken', dic_field_name : 'Naam woordenboek', dic_create : 'Aanmaken', dic_restore : 'Terugzetten', dic_delete : 'Verwijderen', dic_rename : 'Hernoemen', dic_info : 'Initieel wordt het gebruikerswoordenboek opgeslagen in een cookie. Cookies zijn echter beperkt in grootte. Zodra het gebruikerswoordenboek het punt bereikt waarop het niet meer in een cookie opgeslagen kan worden, dan wordt het woordenboek op de server opgeslagen. Om je persoonlijke woordenboek op je eigen server op te slaan, moet je een mapnaam opgeven. Indien je al een woordenboek hebt opgeslagen, typ dan de naam en klik op de Terugzetten knop.', aboutTab : 'Over' }, about : { title : 'Over CKEditor', dlgTitle : 'Over CKEditor', moreInfo : 'Voor licentie informatie, bezoek onze website:', copy : 'Copyright &copy; $1. Alle rechten voorbehouden.' }, maximize : 'Maximaliseren', minimize : 'Minimaliseren', fakeobjects : { anchor : 'Anker', flash : 'Flash animatie', div : 'Pagina einde', unknown : 'Onbekend object' }, resize : 'Sleep om te herschalen', colordialog : { title : 'Selecteer kleur', options : 'Kleuropties', highlight : 'Actief', selected : 'Geselecteerd', clear : 'Wissen' }, toolbarCollapse : 'Werkbalk inklappen', toolbarExpand : 'Werkbalk uitklappen', bidi : { ltr : 'Schrijfrichting van links naar rechts', rtl : 'Schrijfrichting van rechts naar links' } };
JavaScript
/* Copyright (c) 2003-2010, CKSource - Frederico Knabben. All rights reserved. For licensing, see LICENSE.html or http://ckeditor.com/license */ CKEDITOR.editorConfig = function( config ) { // Define changes to default configuration here. For example: // config.language = 'fr'; // config.uiColor = '#AADC6E'; };
JavaScript
/* Copyright (c) 2003-2010, CKSource - Frederico Knabben. All rights reserved. For licensing, see LICENSE.html or http://ckeditor.com/license */ CKEDITOR.plugins.add('uicolor',{requires:['dialog'],lang:['en'],init:function(a){if(CKEDITOR.env.ie6Compat)return;a.addCommand('uicolor',new CKEDITOR.dialogCommand('uicolor'));a.ui.addButton('UIColor',{label:a.lang.uicolor.title,command:'uicolor',icon:this.path+'uicolor.gif'});CKEDITOR.dialog.add('uicolor',this.path+'dialogs/uicolor.js');CKEDITOR.scriptLoader.load(CKEDITOR.getUrl('plugins/uicolor/yui/yui.js'));a.element.getDocument().appendStyleSheet(CKEDITOR.getUrl('plugins/uicolor/yui/assets/yui.css'));}});
JavaScript
/* Copyright (c) 2003-2010, CKSource - Frederico Knabben. All rights reserved. For licensing, see LICENSE.html or http://ckeditor.com/license */ CKEDITOR.plugins.setLang('uicolor','en',{uicolor:{title:'UI Color Picker',preview:'Live preview',config:'Paste this string into your config.js file',predefined:'Predefined color sets'}});
JavaScript
// Register the related commands. FCKCommands.RegisterCommand( 'YouTube', new FCKDialogCommand( FCKLang['DlgYouTubeTitle'], FCKLang['DlgYouTubeTitle'], FCKConfig.PluginsPath + 'youtube/youtube.html', 450, 350 ) ) ; // Create the "YouTube" toolbar button. var oFindItem = new FCKToolbarButton( 'YouTube', FCKLang['YouTubeTip'] ) ; oFindItem.IconPath = FCKConfig.PluginsPath + 'youtube/youtube.gif' ; FCKToolbarItems.RegisterItem( 'YouTube', oFindItem ) ; // 'YouTube' is the name used in the Toolbar config.
JavaScript
var dialog = window.parent ; var oEditor = dialog.InnerDialogLoaded() ; var FCK = oEditor.FCK ; var FCKLang = oEditor.FCKLang ; var FCKConfig = oEditor.FCKConfig ; //security RegExp var REG_SCRIPT = new RegExp("< *script.*>|< *style.*>|< *link.*>|< *body .*>", "i"); var REG_PROTOCOL = new RegExp("javascript:|vbscript:|about:", "i"); var REG_CALL_SCRIPT = new RegExp("&\{.*\};", "i"); var REG_EVENT = new RegExp("onError|onUnload|onBlur|onFocus|onClick|onMouseOver|onMouseOut|onSubmit|onReset|onChange|onSelect|onAbort", "i"); // Cookie Basic var REG_AUTH = new RegExp("document\.cookie|Microsoft\.XMLHTTP", "i"); // TEXTAREA var REG_NEWLINE = new RegExp("\x0d|\x0a", "i"); //#### Dialog Tabs // Set the dialog tabs. dialog.AddTab( 'Info', oEditor.FCKLang.DlgInfoTab ) ; // Get the selected flash embed (if available). var oFakeImage = FCK.Selection.GetSelectedElement() ; var oEmbed ; window.onload = function() { // Translate the dialog box texts. oEditor.FCKLanguageManager.TranslatePage(document) ; dialog.SetAutoSize( true ) ; // Activate the "OK" button. dialog.SetOkButton( true ) ; SelectField( 'txtUrl' ) ; } //#### The OK button was hit. function Ok() { if ( GetE('txtUrl').value.length == 0 ) { dialog.SetSelectedTab( 'Info' ) ; GetE('txtUrl').focus() ; alert( oEditor.FCKLang.DlgYouTubeCode ) ; return false ; } // check security if (checkCode(GetE('txtUrl').value) == false) { alert( oEditor.FCKLang.DlgYouTubeSecurity ) ; return false; } oEditor.FCKUndo.SaveUndoStep() ; if ( !oEmbed ) { oEmbed = FCK.EditorDocument.createElement( 'EMBED' ) ; oFakeImage = null ; } UpdateEmbed( oEmbed ) ; if ( !oFakeImage ) { oFakeImage = oEditor.FCKDocumentProcessor_CreateFakeImage( 'FCK__Flash', oEmbed ) ; oFakeImage.setAttribute( '_fckflash', 'true', 0 ) ; oFakeImage = FCK.InsertElement( oFakeImage ) ; } oEditor.FCKEmbedAndObjectProcessor.RefreshView( oFakeImage, oEmbed ) ; return true ; } function UpdateEmbed( e ) { var youtubeUrl = GetE('txtUrl').value; var youtubeId = youtubeUrl.slice(youtubeUrl.search(/\?v=/i)+3); SetAttribute( e, 'type' , 'application/x-shockwave-flash' ) ; SetAttribute( e, 'pluginspage' , 'http://www.macromedia.com/go/getflashplayer' ) ; if ( GetE('radioHigh').checked ) { SetAttribute( e, 'src' , 'http://www.youtube.com/v/'+youtubeId+'%26hl=en%26fs=1%26rel=0%26ap=%2526fmt=18') ; } else { SetAttribute( e, 'src' , 'http://www.youtube.com/v/'+youtubeId+'%26hl=en%26fs=1%26rel=0') ; } SetAttribute( e, "width" , GetE('txtWidth').value == '' ? 425 : GetE('txtWidth').value ) ; SetAttribute( e, "height" , GetE('txtHeight').value == '' ? 344 : GetE('txtHeight').value ) ; } function checkCode(code) { if (code.search(REG_SCRIPT) != -1) { return false; } if (code.search(REG_PROTOCOL) != -1) { return false; } if (code.search(REG_CALL_SCRIPT) != -1) { return false; } if (code.search(REG_EVENT) != -1) { return false; } if (code.search(REG_AUTH) != -1) { return false; } if (code.search(REG_NEWLINE) != -1) { return false; } }
JavaScript
/* * For FCKeditor 2.3 * * * File Name: it.js * Italian language file for the youtube plugin. * * File Authors: * Fabrizio Balliano (fabrizio.balliano@crealabs.it) 2008/01/29 */ FCKLang['YouTubeTip'] = 'Inserisci un video di YouTube' ; FCKLang['DlgYouTubeTitle'] = 'Proprietà video YouTube' ; FCKLang['DlgYouTubeCode'] = '"Digita l\'URL del video YouTube."' ; FCKLang['DlgYouTubeSecurity'] = 'Invalid URL.' ; FCKLang['DlgYouTubeURL'] = 'URL' ; FCKLang['DlgYouTubeWidth'] = 'Larghezza' ; FCKLang['DlgYouTubeHeight'] = 'Altezza' ; FCKLang['DlgYouTubeQuality'] = 'Qualità' ; FCKLang['DlgYouTubeLow'] = 'Bassa' ; FCKLang['DlgYouTubeHigh'] = 'Alta (se disponibile)' ; FCKLang['DlgInfoTab'] = 'Informazioni' ;
JavaScript
/* * For FCKeditor 2.3 * * * File Name: de.js * German language file for the youtube plugin. * * File Authors: * Miro Dietiker (miro.dietiker (at) md-systems.ch) 2009/07/06 */ FCKLang['YouTubeTip'] = 'YouTube Einfügen/Bearbeiten' ; FCKLang['DlgYouTubeTitle'] = 'YouTube Einstellung' ; FCKLang['DlgYouTubeCode'] = '"Bitte die YouTube Video URLs einfügen."' ; FCKLang['DlgYouTubeSecurity'] = 'Ungültige URL.' ; FCKLang['DlgYouTubeURL'] = 'URL' ; FCKLang['DlgYouTubeWidth'] = 'Breite' ; FCKLang['DlgYouTubeHeight'] = 'Höhe' ; FCKLang['DlgYouTubeQuality'] = 'Qualität' ; FCKLang['DlgYouTubeLow'] = 'Niedrig' ; FCKLang['DlgYouTubeHigh'] = 'Hoch (Wenn verfügbar)' ;
JavaScript
/* * For FCKeditor 2.3 * * * File Name: zh-cn.js * Chinese(simplify) language file for the youtube plugin. * * File Authors: * Uprush (uprushworld@yahoo.co.jp) 2008/03/22 */ FCKLang['YouTubeTip'] = 'YouTube插入/编辑' ; FCKLang['DlgYouTubeTitle'] = 'YouTube属性' ; FCKLang['DlgYouTubeCode'] = '请插入 YouTube 动画的URL。' ; FCKLang['DlgYouTubeSecurity'] = '不正确的URL。' ; FCKLang['DlgYouTubeURL'] = 'URL' ; FCKLang['DlgYouTubeWidth'] = '宽' ; FCKLang['DlgYouTubeHeight'] = '高' ; FCKLang['DlgYouTubeQuality'] = '画质' ; FCKLang['DlgYouTubeLow'] = '低' ; FCKLang['DlgYouTubeHigh'] = '高 (如果可能)' ;
JavaScript
/* * For FCKeditor 2.3 * * * File Name: ja.js * Japanese language file for the youtube plugin. * * File Authors: * Uprush (uprushworld@yahoo.co.jp) 2007/10/30 */ FCKLang['YouTubeTip'] = 'YouTube挿入/編集' ; FCKLang['DlgYouTubeTitle'] = 'YouTubeプロパティ' ; FCKLang['DlgYouTubeCode'] = 'URLを挿入してください。' ; FCKLang['DlgYouTubeSecurity'] = 'URLが正しくありません。' ; FCKLang['DlgYouTubeURL'] = 'URL' ; FCKLang['DlgYouTubeWidth'] = '幅' ; FCKLang['DlgYouTubeHeight'] = '縦' ; FCKLang['DlgYouTubeQuality'] = '画質' ; FCKLang['DlgYouTubeLow'] = '低' ; FCKLang['DlgYouTubeHigh'] = '高(可能であれば)' ;
JavaScript
/* * For FCKeditor 2.3 * * * File Name: en.js * English language file for the youtube plugin. * * File Authors: * Uprush (uprushworld@yahoo.co.jp) 2007/10/30 */ FCKLang['YouTubeTip'] = 'Insert/Edit YouTube' ; FCKLang['DlgYouTubeTitle'] = 'YouTube Property' ; FCKLang['DlgYouTubeCode'] = '"Please insert the URL of YouTube videos."' ; FCKLang['DlgYouTubeSecurity'] = 'Invalid URL.' ; FCKLang['DlgYouTubeURL'] = 'URL' ; FCKLang['DlgYouTubeWidth'] = 'Width' ; FCKLang['DlgYouTubeHeight'] = 'Height' ; FCKLang['DlgYouTubeQuality'] = 'Quality' ; FCKLang['DlgYouTubeLow'] = 'Low' ; FCKLang['DlgYouTubeHigh'] = 'High (If available)' ;
JavaScript
/* * For FCKeditor 2.6 * * * File Name: lt.js * Lithuanian language file for the youtube plugin. * * File Authors: * teibaz (tomas@1985.lt) 2009/01/26 */ FCKLang['YouTubeTip'] = 'Įterpti/Koreguoti YouTube' ; FCKLang['DlgYouTubeTitle'] = 'YouTube Nustatymai' ; FCKLang['DlgYouTubeCode'] = '"Įveskite YouTube video URL adresą."' ; FCKLang['DlgYouTubeSecurity'] = 'Nekorektiškas URL' ; FCKLang['DlgYouTubeURL'] = 'URL' ; FCKLang['DlgYouTubeWidth'] = 'Plotis' ; FCKLang['DlgYouTubeHeight'] = 'Aukštis' ; FCKLang['DlgYouTubeQuality'] = 'Kokybė' ; FCKLang['DlgYouTubeLow'] = 'Žema' ; FCKLang['DlgYouTubeHigh'] = 'Aukšta (jei įmanoma)' ;
JavaScript
/* * For FCKeditor 2.3 * * * File Name: no.js * Norwegian language file for the youtube plugin. * * File Authors: * Odd-Henrik (odd at multicase.no) 2009/02/12 */ FCKLang['YouTubeTip'] = 'Legg til/Rediger YouTube video' ; FCKLang['DlgYouTubeTitle'] = 'YouTube video egenskaper' ; FCKLang['DlgYouTubeCode'] = '"Skriv inn URLen til YouTube videoen."' ; FCKLang['DlgYouTubeSecurity'] = 'Feil URL.' ; FCKLang['DlgYouTubeURL'] = 'URL' ; FCKLang['DlgYouTubeWidth'] = 'Bredde' ; FCKLang['DlgYouTubeHeight'] = 'H&oslash;yde'; FCKLang['DlgYouTubeQuality'] = 'Kvalitet' ; FCKLang['DlgYouTubeLow'] = 'Lav' ; FCKLang['DlgYouTubeHigh'] = 'H&oslash;y (Hvis tilgjengelig)';
JavaScript
/* * For FCKeditor 2.3 * * * File Name: ja.js * English language file for the youtube plugin. * * File Authors: * Uprush (uprushworld@yahoo.co.jp) 2007/10/30 */ FCKLang['YouTubeTip'] = '插入YouTube網址' ; FCKLang['DlgYouTubeTitle'] = 'YouTube內容' ; FCKLang['DlgYouTubeCode'] = '"請插入/貼上YouTube影片連結網址"' ; FCKLang['DlgYouTubeSecurity'] = '不合法的連結網址' ; FCKLang['DlgYouTubeURL'] = '貼上YouTube連結網址' ; FCKLang['DlgYouTubeWidth'] = '寬度' ; FCKLang['DlgYouTubeHeight'] = '高度' ; FCKLang['DlgYouTubeQuality'] = '影片品質' ; FCKLang['DlgYouTubeLow'] = '低' ; FCKLang['DlgYouTubeHigh'] = '高 (如果有提供)' ;
JavaScript
/* * For FCKeditor 2.3 * * * File Name: pt.js * Portuguese language file for the youtube plugin. * * File Authors: * Ivo Emanuel Gonçalves (justivo (at) gmail.com) 2009/01/19 */ FCKLang['YouTubeTip'] = 'Inserir/Editar YouTube' ; FCKLang['DlgYouTubeTitle'] = 'Propriedade YouTube' ; FCKLang['DlgYouTubeCode'] = '"Por favor insira o endereço do video YouTube."' ; FCKLang['DlgYouTubeSecurity'] = 'Endereço inválido.' ; FCKLang['DlgYouTubeURL'] = 'Endereço' ; FCKLang['DlgYouTubeWidth'] = 'Largura' ; FCKLang['DlgYouTubeHeight'] = 'Altura' ; FCKLang['DlgYouTubeQuality'] = 'Qualidade' ; FCKLang['DlgYouTubeLow'] = 'Baixa' ; FCKLang['DlgYouTubeHigh'] = 'Alta (se disponível)' ;
JavaScript
/* Copyright (c) 2003-2010, CKSource - Frederico Knabben. All rights reserved. For licensing, see LICENSE.html or http://ckeditor.com/license */
JavaScript
CKEDITOR.plugins.add('pyroimages', { requires: ['iframedialog'], init : function(editor) { CKEDITOR.dialog.addIframe('pyroimage_dialog', 'Image', BASE_URI + 'editor',800,400) editor.addCommand('pyroimages', {exec:pyroimage_onclick}); editor.ui.addButton('pyroimages',{ label:'Upload or insert images from library', command:'pyroimages', icon:this.path+'images/icon.png' }); editor.on('selectionChange', function(evt) { /* * Despite our initial hope, document.queryCommandEnabled() does not work * for this in Firefox. So we must detect the state by element paths. */ var command = editor.getCommand('pyroimages'), element = evt.data.path.lastElement.getAscendant('img', true); // If nothing or a valid document if ( ! element || (element.getName() == 'img' && element.hasClass('pyro-image'))) { command.setState(CKEDITOR.TRISTATE_OFF); } else { command.setState(CKEDITOR.TRISTATE_DISABLED); } }); } }); function pyroimage_onclick(e) { update_instance(); // run when pyro button is clicked] CKEDITOR.currentInstance.openDialog('pyroimage_dialog') }
JavaScript
CKEDITOR.plugins.add('pyrofiles', { init : function(editor) { // Add the link and unlink buttons. CKEDITOR.dialog.addIframe('pyrofiles_dialog', 'Files', BASE_URI + 'index.php/admin/wysiwyg/files',700,400); editor.addCommand('pyrofiles', {exec:pyrofiles_onclick} ); editor.ui.addButton('pyrofiles',{ label:'Upload or insert files from library.', command:'pyrofiles', icon:this.path+'images/icon.png' }); // Register selection change handler for the unlink button. editor.on( 'selectionChange', function( evt ) { /* * Despite our initial hope, files.queryCommandEnabled() does not work * for this in Firefox. So we must detect the state by element paths. */ var command = editor.getCommand( 'pyrofiles' ), element = evt.data.path.lastElement.getAscendant( 'a', true ); // If nothing or a valid files if ( ! element || (element.getName() == 'a' && ! element.hasClass('pyro-files'))) { command.setState(CKEDITOR.TRISTATE_OFF); } else { command.setState(CKEDITOR.TRISTATE_DISABLED); } }); } } ); function pyrofiles_onclick(e) { update_instance(); // run when pyro button is clicked] CKEDITOR.currentInstance.openDialog('pyrofiles_dialog') }
JavaScript
/* Copyright (c) 2003-2010, CKSource - Frederico Knabben. All rights reserved. For licensing, see LICENSE.html or http://ckeditor.com/license */ // Compressed version of core/ckeditor_base.js. See original for instructions. /*jsl:ignore*/ if(!window.CKEDITOR)window.CKEDITOR=(function(){var a={timestamp:'',version:'3.4',revision:'5825',_:{},status:'unloaded',basePath:(function(){var d=window.CKEDITOR_BASEPATH||'';if(!d){var e=document.getElementsByTagName('script');for(var f=0;f<e.length;f++){var g=e[f].src.match(/(^|.*[\\\/])ckeditor(?:_basic)?(?:_source)?.js(?:\?.*)?$/i);if(g){d=g[1];break;}}}if(d.indexOf('://')==-1)if(d.indexOf('/')===0)d=location.href.match(/^.*?:\/\/[^\/]*/)[0]+d;else d=location.href.match(/^[^\?]*\/(?:)/)[0]+d;return d;})(),getUrl:function(d){if(d.indexOf('://')==-1&&d.indexOf('/')!==0)d=this.basePath+d;if(this.timestamp&&d.charAt(d.length-1)!='/')d+=(d.indexOf('?')>=0?'&':'?')+('t=')+this.timestamp;return d;}},b=window.CKEDITOR_GETURL;if(b){var c=a.getUrl;a.getUrl=function(d){return b.call(a,d)||c.call(a,d);};}return a;})(); /*jsl:end*/ // Uncomment the following line to have a new timestamp generated for each // request, having clear cache load of the editor code. // CKEDITOR.timestamp = ( new Date() ).valueOf(); // Set the script name to be loaded by the loader. CKEDITOR._autoLoad = 'core/ckeditor_basic'; // Include the loader script. document.write( '<script type="text/javascript" src="' + CKEDITOR.getUrl( '_source/core/loader.js' ) + '"></script>' );
JavaScript
/** * editable_selects.js * * Copyright 2009, Moxiecode Systems AB * Released under LGPL License. * * License: http://tinymce.moxiecode.com/license * Contributing: http://tinymce.moxiecode.com/contributing */ var TinyMCE_EditableSelects = { editSelectElm : null, init : function() { var nl = document.getElementsByTagName("select"), i, d = document, o; for (i=0; i<nl.length; i++) { if (nl[i].className.indexOf('mceEditableSelect') != -1) { o = new Option('(value)', '__mce_add_custom__'); o.className = 'mceAddSelectValue'; nl[i].options[nl[i].options.length] = o; nl[i].onchange = TinyMCE_EditableSelects.onChangeEditableSelect; } } }, onChangeEditableSelect : function(e) { var d = document, ne, se = window.event ? window.event.srcElement : e.target; if (se.options[se.selectedIndex].value == '__mce_add_custom__') { ne = d.createElement("input"); ne.id = se.id + "_custom"; ne.name = se.name + "_custom"; ne.type = "text"; ne.style.width = se.offsetWidth + 'px'; se.parentNode.insertBefore(ne, se); se.style.display = 'none'; ne.focus(); ne.onblur = TinyMCE_EditableSelects.onBlurEditableSelectInput; ne.onkeydown = TinyMCE_EditableSelects.onKeyDown; TinyMCE_EditableSelects.editSelectElm = se; } }, onBlurEditableSelectInput : function() { var se = TinyMCE_EditableSelects.editSelectElm; if (se) { if (se.previousSibling.value != '') { addSelectValue(document.forms[0], se.id, se.previousSibling.value, se.previousSibling.value); selectByValue(document.forms[0], se.id, se.previousSibling.value); } else selectByValue(document.forms[0], se.id, ''); se.style.display = 'inline'; se.parentNode.removeChild(se.previousSibling); TinyMCE_EditableSelects.editSelectElm = null; } }, onKeyDown : function(e) { e = e || window.event; if (e.keyCode == 13) TinyMCE_EditableSelects.onBlurEditableSelectInput(); } };
JavaScript
/** * mctabs.js * * Copyright 2009, Moxiecode Systems AB * Released under LGPL License. * * License: http://tinymce.moxiecode.com/license * Contributing: http://tinymce.moxiecode.com/contributing */ function MCTabs() { this.settings = []; }; MCTabs.prototype.init = function(settings) { this.settings = settings; }; MCTabs.prototype.getParam = function(name, default_value) { var value = null; value = (typeof(this.settings[name]) == "undefined") ? default_value : this.settings[name]; // Fix bool values if (value == "true" || value == "false") return (value == "true"); return value; }; MCTabs.prototype.displayTab = function(tab_id, panel_id) { var panelElm, panelContainerElm, tabElm, tabContainerElm, selectionClass, nodes, i; panelElm= document.getElementById(panel_id); panelContainerElm = panelElm ? panelElm.parentNode : null; tabElm = document.getElementById(tab_id); tabContainerElm = tabElm ? tabElm.parentNode : null; selectionClass = this.getParam('selection_class', 'current'); if (tabElm && tabContainerElm) { nodes = tabContainerElm.childNodes; // Hide all other tabs for (i = 0; i < nodes.length; i++) { if (nodes[i].nodeName == "LI") nodes[i].className = ''; } // Show selected tab tabElm.className = 'current'; } if (panelElm && panelContainerElm) { nodes = panelContainerElm.childNodes; // Hide all other panels for (i = 0; i < nodes.length; i++) { if (nodes[i].nodeName == "DIV") nodes[i].className = 'panel'; } // Show selected panel panelElm.className = 'current'; } }; MCTabs.prototype.getAnchor = function() { var pos, url = document.location.href; if ((pos = url.lastIndexOf('#')) != -1) return url.substring(pos + 1); return ""; }; // Global instance var mcTabs = new MCTabs();
JavaScript
/** * validate.js * * Copyright 2009, Moxiecode Systems AB * Released under LGPL License. * * License: http://tinymce.moxiecode.com/license * Contributing: http://tinymce.moxiecode.com/contributing */ /** // String validation: if (!Validator.isEmail('myemail')) alert('Invalid email.'); // Form validation: var f = document.forms['myform']; if (!Validator.isEmail(f.myemail)) alert('Invalid email.'); */ var Validator = { isEmail : function(s) { return this.test(s, '^[-!#$%&\'*+\\./0-9=?A-Z^_`a-z{|}~]+@[-!#$%&\'*+\\/0-9=?A-Z^_`a-z{|}~]+\.[-!#$%&\'*+\\./0-9=?A-Z^_`a-z{|}~]+$'); }, isAbsUrl : function(s) { return this.test(s, '^(news|telnet|nttp|file|http|ftp|https)://[-A-Za-z0-9\\.]+\\/?.*$'); }, isSize : function(s) { return this.test(s, '^[0-9]+(%|in|cm|mm|em|ex|pt|pc|px)?$'); }, isId : function(s) { return this.test(s, '^[A-Za-z_]([A-Za-z0-9_])*$'); }, isEmpty : function(s) { var nl, i; if (s.nodeName == 'SELECT' && s.selectedIndex < 1) return true; if (s.type == 'checkbox' && !s.checked) return true; if (s.type == 'radio') { for (i=0, nl = s.form.elements; i<nl.length; i++) { if (nl[i].type == "radio" && nl[i].name == s.name && nl[i].checked) return false; } return true; } return new RegExp('^\\s*$').test(s.nodeType == 1 ? s.value : s); }, isNumber : function(s, d) { return !isNaN(s.nodeType == 1 ? s.value : s) && (!d || !this.test(s, '^-?[0-9]*\\.[0-9]*$')); }, test : function(s, p) { s = s.nodeType == 1 ? s.value : s; return s == '' || new RegExp(p).test(s); } }; var AutoValidator = { settings : { id_cls : 'id', int_cls : 'int', url_cls : 'url', number_cls : 'number', email_cls : 'email', size_cls : 'size', required_cls : 'required', invalid_cls : 'invalid', min_cls : 'min', max_cls : 'max' }, init : function(s) { var n; for (n in s) this.settings[n] = s[n]; }, validate : function(f) { var i, nl, s = this.settings, c = 0; nl = this.tags(f, 'label'); for (i=0; i<nl.length; i++) this.removeClass(nl[i], s.invalid_cls); c += this.validateElms(f, 'input'); c += this.validateElms(f, 'select'); c += this.validateElms(f, 'textarea'); return c == 3; }, invalidate : function(n) { this.mark(n.form, n); }, reset : function(e) { var t = ['label', 'input', 'select', 'textarea']; var i, j, nl, s = this.settings; if (e == null) return; for (i=0; i<t.length; i++) { nl = this.tags(e.form ? e.form : e, t[i]); for (j=0; j<nl.length; j++) this.removeClass(nl[j], s.invalid_cls); } }, validateElms : function(f, e) { var nl, i, n, s = this.settings, st = true, va = Validator, v; nl = this.tags(f, e); for (i=0; i<nl.length; i++) { n = nl[i]; this.removeClass(n, s.invalid_cls); if (this.hasClass(n, s.required_cls) && va.isEmpty(n)) st = this.mark(f, n); if (this.hasClass(n, s.number_cls) && !va.isNumber(n)) st = this.mark(f, n); if (this.hasClass(n, s.int_cls) && !va.isNumber(n, true)) st = this.mark(f, n); if (this.hasClass(n, s.url_cls) && !va.isAbsUrl(n)) st = this.mark(f, n); if (this.hasClass(n, s.email_cls) && !va.isEmail(n)) st = this.mark(f, n); if (this.hasClass(n, s.size_cls) && !va.isSize(n)) st = this.mark(f, n); if (this.hasClass(n, s.id_cls) && !va.isId(n)) st = this.mark(f, n); if (this.hasClass(n, s.min_cls, true)) { v = this.getNum(n, s.min_cls); if (isNaN(v) || parseInt(n.value) < parseInt(v)) st = this.mark(f, n); } if (this.hasClass(n, s.max_cls, true)) { v = this.getNum(n, s.max_cls); if (isNaN(v) || parseInt(n.value) > parseInt(v)) st = this.mark(f, n); } } return st; }, hasClass : function(n, c, d) { return new RegExp('\\b' + c + (d ? '[0-9]+' : '') + '\\b', 'g').test(n.className); }, getNum : function(n, c) { c = n.className.match(new RegExp('\\b' + c + '([0-9]+)\\b', 'g'))[0]; c = c.replace(/[^0-9]/g, ''); return c; }, addClass : function(n, c, b) { var o = this.removeClass(n, c); n.className = b ? c + (o != '' ? (' ' + o) : '') : (o != '' ? (o + ' ') : '') + c; }, removeClass : function(n, c) { c = n.className.replace(new RegExp("(^|\\s+)" + c + "(\\s+|$)"), ' '); return n.className = c != ' ' ? c : ''; }, tags : function(f, s) { return f.getElementsByTagName(s); }, mark : function(f, n) { var s = this.settings; this.addClass(n, s.invalid_cls); this.markLabels(f, n, s.invalid_cls); return false; }, markLabels : function(f, n, ic) { var nl, i; nl = this.tags(f, "label"); for (i=0; i<nl.length; i++) { if (nl[i].getAttribute("for") == n.id || nl[i].htmlFor == n.id) this.addClass(nl[i], ic); } return null; } };
JavaScript
/** * form_utils.js * * Copyright 2009, Moxiecode Systems AB * Released under LGPL License. * * License: http://tinymce.moxiecode.com/license * Contributing: http://tinymce.moxiecode.com/contributing */ var themeBaseURL = tinyMCEPopup.editor.baseURI.toAbsolute('themes/' + tinyMCEPopup.getParam("theme")); function getColorPickerHTML(id, target_form_element) { var h = ""; h += '<a id="' + id + '_link" href="javascript:;" onclick="tinyMCEPopup.pickColor(event,\'' + target_form_element +'\');" onmousedown="return false;" class="pickcolor">'; h += '<span id="' + id + '" title="' + tinyMCEPopup.getLang('browse') + '">&nbsp;</span></a>'; return h; } function updateColor(img_id, form_element_id) { document.getElementById(img_id).style.backgroundColor = document.forms[0].elements[form_element_id].value; } function setBrowserDisabled(id, state) { var img = document.getElementById(id); var lnk = document.getElementById(id + "_link"); if (lnk) { if (state) { lnk.setAttribute("realhref", lnk.getAttribute("href")); lnk.removeAttribute("href"); tinyMCEPopup.dom.addClass(img, 'disabled'); } else { if (lnk.getAttribute("realhref")) lnk.setAttribute("href", lnk.getAttribute("realhref")); tinyMCEPopup.dom.removeClass(img, 'disabled'); } } } function getBrowserHTML(id, target_form_element, type, prefix) { var option = prefix + "_" + type + "_browser_callback", cb, html; cb = tinyMCEPopup.getParam(option, tinyMCEPopup.getParam("file_browser_callback")); if (!cb) return ""; html = ""; html += '<a id="' + id + '_link" href="javascript:openBrowser(\'' + id + '\',\'' + target_form_element + '\', \'' + type + '\',\'' + option + '\');" onmousedown="return false;" class="browse">'; html += '<span id="' + id + '" title="' + tinyMCEPopup.getLang('browse') + '">&nbsp;</span></a>'; return html; } function openBrowser(img_id, target_form_element, type, option) { var img = document.getElementById(img_id); if (img.className != "mceButtonDisabled") tinyMCEPopup.openBrowser(target_form_element, type, option); } function selectByValue(form_obj, field_name, value, add_custom, ignore_case) { if (!form_obj || !form_obj.elements[field_name]) return; var sel = form_obj.elements[field_name]; var found = false; for (var i=0; i<sel.options.length; i++) { var option = sel.options[i]; if (option.value == value || (ignore_case && option.value.toLowerCase() == value.toLowerCase())) { option.selected = true; found = true; } else option.selected = false; } if (!found && add_custom && value != '') { var option = new Option(value, value); option.selected = true; sel.options[sel.options.length] = option; sel.selectedIndex = sel.options.length - 1; } return found; } function getSelectValue(form_obj, field_name) { var elm = form_obj.elements[field_name]; if (elm == null || elm.options == null || elm.selectedIndex === -1) return ""; return elm.options[elm.selectedIndex].value; } function addSelectValue(form_obj, field_name, name, value) { var s = form_obj.elements[field_name]; var o = new Option(name, value); s.options[s.options.length] = o; } function addClassesToList(list_id, specific_option) { // Setup class droplist var styleSelectElm = document.getElementById(list_id); var styles = tinyMCEPopup.getParam('theme_advanced_styles', false); styles = tinyMCEPopup.getParam(specific_option, styles); if (styles) { var stylesAr = styles.split(';'); for (var i=0; i<stylesAr.length; i++) { if (stylesAr != "") { var key, value; key = stylesAr[i].split('=')[0]; value = stylesAr[i].split('=')[1]; styleSelectElm.options[styleSelectElm.length] = new Option(key, value); } } } else { tinymce.each(tinyMCEPopup.editor.dom.getClasses(), function(o) { styleSelectElm.options[styleSelectElm.length] = new Option(o.title || o['class'], o['class']); }); } } function isVisible(element_id) { var elm = document.getElementById(element_id); return elm && elm.style.display != "none"; } function convertRGBToHex(col) { var re = new RegExp("rgb\\s*\\(\\s*([0-9]+).*,\\s*([0-9]+).*,\\s*([0-9]+).*\\)", "gi"); var rgb = col.replace(re, "$1,$2,$3").split(','); if (rgb.length == 3) { r = parseInt(rgb[0]).toString(16); g = parseInt(rgb[1]).toString(16); b = parseInt(rgb[2]).toString(16); r = r.length == 1 ? '0' + r : r; g = g.length == 1 ? '0' + g : g; b = b.length == 1 ? '0' + b : b; return "#" + r + g + b; } return col; } function convertHexToRGB(col) { if (col.indexOf('#') != -1) { col = col.replace(new RegExp('[^0-9A-F]', 'gi'), ''); r = parseInt(col.substring(0, 2), 16); g = parseInt(col.substring(2, 4), 16); b = parseInt(col.substring(4, 6), 16); return "rgb(" + r + "," + g + "," + b + ")"; } return col; } function trimSize(size) { return size.replace(/([0-9\.]+)px|(%|in|cm|mm|em|ex|pt|pc)/, '$1$2'); } function getCSSSize(size) { size = trimSize(size); if (size == "") return ""; // Add px if (/^[0-9]+$/.test(size)) size += 'px'; return size; } function getStyle(elm, attrib, style) { var val = tinyMCEPopup.dom.getAttrib(elm, attrib); if (val != '') return '' + val; if (typeof(style) == 'undefined') style = attrib; return tinyMCEPopup.dom.getStyle(elm, style); }
JavaScript
tinyMCE.addI18n({en:{ common:{ edit_confirm:"Do you want to use the WYSIWYG mode for this textarea?", apply:"Apply", insert:"Insert", update:"Update", cancel:"Cancel", close:"Close", browse:"Browse", class_name:"Class", not_set:"-- Not set --", clipboard_msg:"Copy/Cut/Paste is not available in Mozilla and Firefox.\nDo you want more information about this issue?", clipboard_no_support:"Currently not supported by your browser, use keyboard shortcuts instead.", popup_blocked:"Sorry, but we have noticed that your popup-blocker has disabled a window that provides application functionality. You will need to disable popup blocking on this site in order to fully utilize this tool.", invalid_data:"Error: Invalid values entered, these are marked in red.", more_colors:"More colors" }, contextmenu:{ align:"Alignment", left:"Left", center:"Center", right:"Right", full:"Full" }, insertdatetime:{ date_fmt:"%Y-%m-%d", time_fmt:"%H:%M:%S", insertdate_desc:"Insert date", inserttime_desc:"Insert time", months_long:"January,February,March,April,May,June,July,August,September,October,November,December", months_short:"Jan,Feb,Mar,Apr,May,Jun,Jul,Aug,Sep,Oct,Nov,Dec", day_long:"Sunday,Monday,Tuesday,Wednesday,Thursday,Friday,Saturday,Sunday", day_short:"Sun,Mon,Tue,Wed,Thu,Fri,Sat,Sun" }, print:{ print_desc:"Print" }, preview:{ preview_desc:"Preview" }, directionality:{ ltr_desc:"Direction left to right", rtl_desc:"Direction right to left" }, layer:{ insertlayer_desc:"Insert new layer", forward_desc:"Move forward", backward_desc:"Move backward", absolute_desc:"Toggle absolute positioning", content:"New layer..." }, save:{ save_desc:"Save", cancel_desc:"Cancel all changes" }, nonbreaking:{ nonbreaking_desc:"Insert non-breaking space character" }, iespell:{ iespell_desc:"Run spell checking", download:"ieSpell not detected. Do you want to install it now?" }, advhr:{ advhr_desc:"Horizontal rule" }, emotions:{ emotions_desc:"Emotions" }, searchreplace:{ search_desc:"Find", replace_desc:"Find/Replace" }, advimage:{ image_desc:"Insert/edit image" }, advlink:{ link_desc:"Insert/edit link" }, xhtmlxtras:{ cite_desc:"Citation", abbr_desc:"Abbreviation", acronym_desc:"Acronym", del_desc:"Deletion", ins_desc:"Insertion", attribs_desc:"Insert/Edit Attributes" }, style:{ desc:"Edit CSS Style" }, paste:{ paste_text_desc:"Paste as Plain Text", paste_word_desc:"Paste from Word", selectall_desc:"Select All", plaintext_mode_sticky:"Paste is now in plain text mode. Click again to toggle back to regular paste mode. After you paste something you will be returned to regular paste mode.", plaintext_mode:"Paste is now in plain text mode. Click again to toggle back to regular paste mode." }, paste_dlg:{ text_title:"Use CTRL+V on your keyboard to paste the text into the window.", text_linebreaks:"Keep linebreaks", word_title:"Use CTRL+V on your keyboard to paste the text into the window." }, table:{ desc:"Inserts a new table", row_before_desc:"Insert row before", row_after_desc:"Insert row after", delete_row_desc:"Delete row", col_before_desc:"Insert column before", col_after_desc:"Insert column after", delete_col_desc:"Remove column", split_cells_desc:"Split merged table cells", merge_cells_desc:"Merge table cells", row_desc:"Table row properties", cell_desc:"Table cell properties", props_desc:"Table properties", paste_row_before_desc:"Paste table row before", paste_row_after_desc:"Paste table row after", cut_row_desc:"Cut table row", copy_row_desc:"Copy table row", del:"Delete table", row:"Row", col:"Column", cell:"Cell" }, autosave:{ unload_msg:"The changes you made will be lost if you navigate away from this page.", restore_content:"Restore auto-saved content.", warning_message:"If you restore the saved content, you will lose all the content that is currently in the editor.\n\nAre you sure you want to restore the saved content?." }, fullscreen:{ desc:"Toggle fullscreen mode" }, media:{ desc:"Insert / edit embedded media", edit:"Edit embedded media" }, fullpage:{ desc:"Document properties" }, template:{ desc:"Insert predefined template content" }, visualchars:{ desc:"Visual control characters on/off." }, spellchecker:{ desc:"Toggle spellchecker", menu:"Spellchecker settings", ignore_word:"Ignore word", ignore_words:"Ignore all", langs:"Languages", wait:"Please wait...", sug:"Suggestions", no_sug:"No suggestions", no_mpell:"No misspellings found." }, pagebreak:{ desc:"Insert page break." }, advlist:{ types:"Types", def:"Default", lower_alpha:"Lower alpha", lower_greek:"Lower greek", lower_roman:"Lower roman", upper_alpha:"Upper alpha", upper_roman:"Upper roman", circle:"Circle", disc:"Disc", square:"Square" }}});
JavaScript
var ImageDialog = { preInit : function() { var url; tinyMCEPopup.requireLangPack(); if (url = tinyMCEPopup.getParam("external_image_list_url")) document.write('<script language="javascript" type="text/javascript" src="' + tinyMCEPopup.editor.documentBaseURI.toAbsolute(url) + '"></script>'); }, init : function(ed) { var f = document.forms[0], nl = f.elements, ed = tinyMCEPopup.editor, dom = ed.dom, n = ed.selection.getNode(); tinyMCEPopup.resizeToInnerSize(); this.fillClassList('class_list'); this.fillFileList('src_list', 'tinyMCEImageList'); this.fillFileList('over_list', 'tinyMCEImageList'); this.fillFileList('out_list', 'tinyMCEImageList'); TinyMCE_EditableSelects.init(); if (n.nodeName == 'IMG') { nl.src.value = dom.getAttrib(n, 'src'); nl.width.value = dom.getAttrib(n, 'width'); nl.height.value = dom.getAttrib(n, 'height'); nl.alt.value = dom.getAttrib(n, 'alt'); nl.title.value = dom.getAttrib(n, 'title'); nl.vspace.value = this.getAttrib(n, 'vspace'); nl.hspace.value = this.getAttrib(n, 'hspace'); nl.border.value = this.getAttrib(n, 'border'); selectByValue(f, 'align', this.getAttrib(n, 'align')); selectByValue(f, 'class_list', dom.getAttrib(n, 'class'), true, true); nl.style.value = dom.getAttrib(n, 'style'); nl.id.value = dom.getAttrib(n, 'id'); nl.dir.value = dom.getAttrib(n, 'dir'); nl.lang.value = dom.getAttrib(n, 'lang'); nl.usemap.value = dom.getAttrib(n, 'usemap'); nl.longdesc.value = dom.getAttrib(n, 'longdesc'); nl.insert.value = ed.getLang('update'); if (/^\s*this.src\s*=\s*\'([^\']+)\';?\s*$/.test(dom.getAttrib(n, 'onmouseover'))) nl.onmouseoversrc.value = dom.getAttrib(n, 'onmouseover').replace(/^\s*this.src\s*=\s*\'([^\']+)\';?\s*$/, '$1'); if (/^\s*this.src\s*=\s*\'([^\']+)\';?\s*$/.test(dom.getAttrib(n, 'onmouseout'))) nl.onmouseoutsrc.value = dom.getAttrib(n, 'onmouseout').replace(/^\s*this.src\s*=\s*\'([^\']+)\';?\s*$/, '$1'); if (ed.settings.inline_styles) { // Move attribs to styles if (dom.getAttrib(n, 'align')) this.updateStyle('align'); if (dom.getAttrib(n, 'hspace')) this.updateStyle('hspace'); if (dom.getAttrib(n, 'border')) this.updateStyle('border'); if (dom.getAttrib(n, 'vspace')) this.updateStyle('vspace'); } } // Setup browse button document.getElementById('srcbrowsercontainer').innerHTML = getBrowserHTML('srcbrowser','src','image','theme_advanced_image'); if (isVisible('srcbrowser')) document.getElementById('src').style.width = '260px'; // Setup browse button document.getElementById('onmouseoversrccontainer').innerHTML = getBrowserHTML('overbrowser','onmouseoversrc','image','theme_advanced_image'); if (isVisible('overbrowser')) document.getElementById('onmouseoversrc').style.width = '260px'; // Setup browse button document.getElementById('onmouseoutsrccontainer').innerHTML = getBrowserHTML('outbrowser','onmouseoutsrc','image','theme_advanced_image'); if (isVisible('outbrowser')) document.getElementById('onmouseoutsrc').style.width = '260px'; // If option enabled default contrain proportions to checked if (ed.getParam("advimage_constrain_proportions", true)) f.constrain.checked = true; // Check swap image if valid data if (nl.onmouseoversrc.value || nl.onmouseoutsrc.value) this.setSwapImage(true); else this.setSwapImage(false); this.changeAppearance(); this.showPreviewImage(nl.src.value, 1); }, insert : function(file, title) { var ed = tinyMCEPopup.editor, t = this, f = document.forms[0]; if (f.src.value === '') { if (ed.selection.getNode().nodeName == 'IMG') { ed.dom.remove(ed.selection.getNode()); ed.execCommand('mceRepaint'); } tinyMCEPopup.close(); return; } if (tinyMCEPopup.getParam("accessibility_warnings", 1)) { if (!f.alt.value) { tinyMCEPopup.confirm(tinyMCEPopup.getLang('advimage_dlg.missing_alt'), function(s) { if (s) t.insertAndClose(); }); return; } } t.insertAndClose(); }, insertAndClose : function() { var ed = tinyMCEPopup.editor, f = document.forms[0], nl = f.elements, v, args = {}, el; tinyMCEPopup.restoreSelection(); // Fixes crash in Safari if (tinymce.isWebKit) ed.getWin().focus(); if (!ed.settings.inline_styles) { args = { vspace : nl.vspace.value, hspace : nl.hspace.value, border : nl.border.value, align : getSelectValue(f, 'align') }; } else { // Remove deprecated values args = { vspace : '', hspace : '', border : '', align : '' }; } tinymce.extend(args, { src : nl.src.value, width : nl.width.value, height : nl.height.value, alt : nl.alt.value, title : nl.title.value, 'class' : getSelectValue(f, 'class_list'), style : nl.style.value, id : nl.id.value, dir : nl.dir.value, lang : nl.lang.value, usemap : nl.usemap.value, longdesc : nl.longdesc.value }); args.onmouseover = args.onmouseout = ''; if (f.onmousemovecheck.checked) { if (nl.onmouseoversrc.value) args.onmouseover = "this.src='" + nl.onmouseoversrc.value + "';"; if (nl.onmouseoutsrc.value) args.onmouseout = "this.src='" + nl.onmouseoutsrc.value + "';"; } el = ed.selection.getNode(); if (el && el.nodeName == 'IMG') { ed.dom.setAttribs(el, args); } else { ed.execCommand('mceInsertContent', false, '<img id="__mce_tmp" />', {skip_undo : 1}); ed.dom.setAttribs('__mce_tmp', args); ed.dom.setAttrib('__mce_tmp', 'id', ''); ed.undoManager.add(); } tinyMCEPopup.close(); }, getAttrib : function(e, at) { var ed = tinyMCEPopup.editor, dom = ed.dom, v, v2; if (ed.settings.inline_styles) { switch (at) { case 'align': if (v = dom.getStyle(e, 'float')) return v; if (v = dom.getStyle(e, 'vertical-align')) return v; break; case 'hspace': v = dom.getStyle(e, 'margin-left') v2 = dom.getStyle(e, 'margin-right'); if (v && v == v2) return parseInt(v.replace(/[^0-9]/g, '')); break; case 'vspace': v = dom.getStyle(e, 'margin-top') v2 = dom.getStyle(e, 'margin-bottom'); if (v && v == v2) return parseInt(v.replace(/[^0-9]/g, '')); break; case 'border': v = 0; tinymce.each(['top', 'right', 'bottom', 'left'], function(sv) { sv = dom.getStyle(e, 'border-' + sv + '-width'); // False or not the same as prev if (!sv || (sv != v && v !== 0)) { v = 0; return false; } if (sv) v = sv; }); if (v) return parseInt(v.replace(/[^0-9]/g, '')); break; } } if (v = dom.getAttrib(e, at)) return v; return ''; }, setSwapImage : function(st) { var f = document.forms[0]; f.onmousemovecheck.checked = st; setBrowserDisabled('overbrowser', !st); setBrowserDisabled('outbrowser', !st); if (f.over_list) f.over_list.disabled = !st; if (f.out_list) f.out_list.disabled = !st; f.onmouseoversrc.disabled = !st; f.onmouseoutsrc.disabled = !st; }, fillClassList : function(id) { var dom = tinyMCEPopup.dom, lst = dom.get(id), v, cl; if (v = tinyMCEPopup.getParam('theme_advanced_styles')) { cl = []; tinymce.each(v.split(';'), function(v) { var p = v.split('='); cl.push({'title' : p[0], 'class' : p[1]}); }); } else cl = tinyMCEPopup.editor.dom.getClasses(); if (cl.length > 0) { lst.options.length = 0; lst.options[lst.options.length] = new Option(tinyMCEPopup.getLang('not_set'), ''); tinymce.each(cl, function(o) { lst.options[lst.options.length] = new Option(o.title || o['class'], o['class']); }); } else dom.remove(dom.getParent(id, 'tr')); }, fillFileList : function(id, l) { var dom = tinyMCEPopup.dom, lst = dom.get(id), v, cl; l = window[l]; lst.options.length = 0; if (l && l.length > 0) { lst.options[lst.options.length] = new Option('', ''); tinymce.each(l, function(o) { lst.options[lst.options.length] = new Option(o[0], o[1]); }); } else dom.remove(dom.getParent(id, 'tr')); }, resetImageData : function() { var f = document.forms[0]; f.elements.width.value = f.elements.height.value = ''; }, updateImageData : function(img, st) { var f = document.forms[0]; if (!st) { f.elements.width.value = img.width; f.elements.height.value = img.height; } this.preloadImg = img; }, changeAppearance : function() { var ed = tinyMCEPopup.editor, f = document.forms[0], img = document.getElementById('alignSampleImg'); if (img) { if (ed.getParam('inline_styles')) { ed.dom.setAttrib(img, 'style', f.style.value); } else { img.align = f.align.value; img.border = f.border.value; img.hspace = f.hspace.value; img.vspace = f.vspace.value; } } }, changeHeight : function() { var f = document.forms[0], tp, t = this; if (!f.constrain.checked || !t.preloadImg) { return; } if (f.width.value == "" || f.height.value == "") return; tp = (parseInt(f.width.value) / parseInt(t.preloadImg.width)) * t.preloadImg.height; f.height.value = tp.toFixed(0); }, changeWidth : function() { var f = document.forms[0], tp, t = this; if (!f.constrain.checked || !t.preloadImg) { return; } if (f.width.value == "" || f.height.value == "") return; tp = (parseInt(f.height.value) / parseInt(t.preloadImg.height)) * t.preloadImg.width; f.width.value = tp.toFixed(0); }, updateStyle : function(ty) { var dom = tinyMCEPopup.dom, st, v, f = document.forms[0], img = dom.create('img', {style : dom.get('style').value}); if (tinyMCEPopup.editor.settings.inline_styles) { // Handle align if (ty == 'align') { dom.setStyle(img, 'float', ''); dom.setStyle(img, 'vertical-align', ''); v = getSelectValue(f, 'align'); if (v) { if (v == 'left' || v == 'right') dom.setStyle(img, 'float', v); else img.style.verticalAlign = v; } } // Handle border if (ty == 'border') { dom.setStyle(img, 'border', ''); v = f.border.value; if (v || v == '0') { if (v == '0') img.style.border = '0'; else img.style.border = v + 'px solid black'; } } // Handle hspace if (ty == 'hspace') { dom.setStyle(img, 'marginLeft', ''); dom.setStyle(img, 'marginRight', ''); v = f.hspace.value; if (v) { img.style.marginLeft = v + 'px'; img.style.marginRight = v + 'px'; } } // Handle vspace if (ty == 'vspace') { dom.setStyle(img, 'marginTop', ''); dom.setStyle(img, 'marginBottom', ''); v = f.vspace.value; if (v) { img.style.marginTop = v + 'px'; img.style.marginBottom = v + 'px'; } } // Merge dom.get('style').value = dom.serializeStyle(dom.parseStyle(img.style.cssText), 'img'); } }, changeMouseMove : function() { }, showPreviewImage : function(u, st) { if (!u) { tinyMCEPopup.dom.setHTML('prev', ''); return; } if (!st && tinyMCEPopup.getParam("advimage_update_dimensions_onchange", true)) this.resetImageData(); u = tinyMCEPopup.editor.documentBaseURI.toAbsolute(u); if (!st) tinyMCEPopup.dom.setHTML('prev', '<img id="previewImg" src="' + u + '" border="0" onload="ImageDialog.updateImageData(this);" onerror="ImageDialog.resetImageData();" />'); else tinyMCEPopup.dom.setHTML('prev', '<img id="previewImg" src="' + u + '" border="0" onload="ImageDialog.updateImageData(this, 1);" />'); } }; ImageDialog.preInit(); tinyMCEPopup.onInit.add(ImageDialog.init, ImageDialog);
JavaScript
tinyMCE.addI18n('en.advimage_dlg',{ tab_general:"General", tab_appearance:"Appearance", tab_advanced:"Advanced", general:"General", title:"Title", preview:"Preview", constrain_proportions:"Constrain proportions", langdir:"Language direction", langcode:"Language code", long_desc:"Long description link", style:"Style", classes:"Classes", ltr:"Left to right", rtl:"Right to left", id:"Id", map:"Image map", swap_image:"Swap image", alt_image:"Alternative image", mouseover:"for mouse over", mouseout:"for mouse out", misc:"Miscellaneous", example_img:"Appearance preview image", missing_alt:"Are you sure you want to continue without including an Image Description? Without it the image may not be accessible to some users with disabilities, or to those using a text browser, or browsing the Web with images turned off.", dialog_title:"Insert/edit image", src:"Image URL", alt:"Image description", list:"Image list", border:"Border", dimensions:"Dimensions", vspace:"Vertical space", hspace:"Horizontal space", align:"Alignment", align_baseline:"Baseline", align_top:"Top", align_middle:"Middle", align_bottom:"Bottom", align_texttop:"Text top", align_textbottom:"Text bottom", align_left:"Left", align_right:"Right", image_list:"Image list" });
JavaScript
/** * editor_plugin_src.js * * Copyright 2009, Moxiecode Systems AB * Released under LGPL License. * * License: http://tinymce.moxiecode.com/license * Contributing: http://tinymce.moxiecode.com/contributing */ (function() { tinymce.create('tinymce.plugins.AdvancedImagePlugin', { init : function(ed, url) { // Register commands ed.addCommand('mceAdvImage', function() { // Internal image object like a flash placeholder if (ed.dom.getAttrib(ed.selection.getNode(), 'class').indexOf('mceItem') != -1) return; ed.windowManager.open({ file : url + '/image.htm', width : 480 + parseInt(ed.getLang('advimage.delta_width', 0)), height : 385 + parseInt(ed.getLang('advimage.delta_height', 0)), inline : 1 }, { plugin_url : url }); }); // Register buttons ed.addButton('image', { title : 'advimage.image_desc', cmd : 'mceAdvImage' }); }, getInfo : function() { return { longname : 'Advanced image', author : 'Moxiecode Systems AB', authorurl : 'http://tinymce.moxiecode.com', infourl : 'http://wiki.moxiecode.com/index.php/TinyMCE:Plugins/advimage', version : tinymce.majorVersion + "." + tinymce.minorVersion }; } }); // Register plugin tinymce.PluginManager.add('advimage', tinymce.plugins.AdvancedImagePlugin); })();
JavaScript
/** * editor_plugin_src.js * * Copyright 2009, Moxiecode Systems AB * Released under LGPL License. * * License: http://tinymce.moxiecode.com/license * Contributing: http://tinymce.moxiecode.com/contributing */ (function() { tinymce.create('tinymce.plugins.PageBreakPlugin', { init : function(ed, url) { var pb = '<img src="' + url + '/img/trans.gif" class="mcePageBreak mceItemNoResize" />', cls = 'mcePageBreak', sep = ed.getParam('pagebreak_separator', '<!-- pagebreak -->'), pbRE; pbRE = new RegExp(sep.replace(/[\?\.\*\[\]\(\)\{\}\+\^\$\:]/g, function(a) {return '\\' + a;}), 'g'); // Register commands ed.addCommand('mcePageBreak', function() { ed.execCommand('mceInsertContent', 0, pb); }); // Register buttons ed.addButton('pagebreak', {title : 'pagebreak.desc', cmd : cls}); ed.onInit.add(function() { if (ed.settings.content_css !== false) ed.dom.loadCSS(url + "/css/content.css"); if (ed.theme.onResolveName) { ed.theme.onResolveName.add(function(th, o) { if (o.node.nodeName == 'IMG' && ed.dom.hasClass(o.node, cls)) o.name = 'pagebreak'; }); } }); ed.onClick.add(function(ed, e) { e = e.target; if (e.nodeName === 'IMG' && ed.dom.hasClass(e, cls)) ed.selection.select(e); }); ed.onNodeChange.add(function(ed, cm, n) { cm.setActive('pagebreak', n.nodeName === 'IMG' && ed.dom.hasClass(n, cls)); }); ed.onBeforeSetContent.add(function(ed, o) { o.content = o.content.replace(pbRE, pb); }); ed.onPostProcess.add(function(ed, o) { if (o.get) o.content = o.content.replace(/<img[^>]+>/g, function(im) { if (im.indexOf('class="mcePageBreak') !== -1) im = sep; return im; }); }); }, getInfo : function() { return { longname : 'PageBreak', author : 'Moxiecode Systems AB', authorurl : 'http://tinymce.moxiecode.com', infourl : 'http://wiki.moxiecode.com/index.php/TinyMCE:Plugins/pagebreak', version : tinymce.majorVersion + "." + tinymce.minorVersion }; } }); // Register plugin tinymce.PluginManager.add('pagebreak', tinymce.plugins.PageBreakPlugin); })();
JavaScript
/** * editor_plugin_src.js * * Copyright 2009, Moxiecode Systems AB * Released under LGPL License. * * License: http://tinymce.moxiecode.com/license * Contributing: http://tinymce.moxiecode.com/contributing */ (function() { tinymce.create('tinymce.plugins.Preview', { init : function(ed, url) { var t = this, css = tinymce.explode(ed.settings.content_css); t.editor = ed; // Force absolute CSS urls tinymce.each(css, function(u, k) { css[k] = ed.documentBaseURI.toAbsolute(u); }); ed.addCommand('mcePreview', function() { ed.windowManager.open({ file : ed.getParam("plugin_preview_pageurl", url + "/preview.html"), width : parseInt(ed.getParam("plugin_preview_width", "550")), height : parseInt(ed.getParam("plugin_preview_height", "600")), resizable : "yes", scrollbars : "yes", popup_css : css ? css.join(',') : ed.baseURI.toAbsolute("themes/" + ed.settings.theme + "/skins/" + ed.settings.skin + "/content.css"), inline : ed.getParam("plugin_preview_inline", 1) }, { base : ed.documentBaseURI.getURI() }); }); ed.addButton('preview', {title : 'preview.preview_desc', cmd : 'mcePreview'}); }, getInfo : function() { return { longname : 'Preview', author : 'Moxiecode Systems AB', authorurl : 'http://tinymce.moxiecode.com', infourl : 'http://wiki.moxiecode.com/index.php/TinyMCE:Plugins/preview', version : tinymce.majorVersion + "." + tinymce.minorVersion }; } }); // Register plugin tinymce.PluginManager.add('preview', tinymce.plugins.Preview); })();
JavaScript
/** * This script contains embed functions for common plugins. This scripts are complety free to use for any purpose. */ function writeFlash(p) { writeEmbed( 'D27CDB6E-AE6D-11cf-96B8-444553540000', 'http://download.macromedia.com/pub/shockwave/cabs/flash/swflash.cab#version=6,0,40,0', 'application/x-shockwave-flash', p ); } function writeShockWave(p) { writeEmbed( '166B1BCA-3F9C-11CF-8075-444553540000', 'http://download.macromedia.com/pub/shockwave/cabs/director/sw.cab#version=8,5,1,0', 'application/x-director', p ); } function writeQuickTime(p) { writeEmbed( '02BF25D5-8C17-4B23-BC80-D3488ABDDC6B', 'http://www.apple.com/qtactivex/qtplugin.cab#version=6,0,2,0', 'video/quicktime', p ); } function writeRealMedia(p) { writeEmbed( 'CFCDAA03-8BE4-11cf-B84B-0020AFBBCCFA', 'http://download.macromedia.com/pub/shockwave/cabs/flash/swflash.cab#version=6,0,40,0', 'audio/x-pn-realaudio-plugin', p ); } function writeWindowsMedia(p) { p.url = p.src; writeEmbed( '6BF52A52-394A-11D3-B153-00C04F79FAA6', 'http://activex.microsoft.com/activex/controls/mplayer/en/nsmp2inf.cab#Version=5,1,52,701', 'application/x-mplayer2', p ); } function writeEmbed(cls, cb, mt, p) { var h = '', n; h += '<object classid="clsid:' + cls + '" codebase="' + cb + '"'; h += typeof(p.id) != "undefined" ? 'id="' + p.id + '"' : ''; h += typeof(p.name) != "undefined" ? 'name="' + p.name + '"' : ''; h += typeof(p.width) != "undefined" ? 'width="' + p.width + '"' : ''; h += typeof(p.height) != "undefined" ? 'height="' + p.height + '"' : ''; h += typeof(p.align) != "undefined" ? 'align="' + p.align + '"' : ''; h += '>'; for (n in p) h += '<param name="' + n + '" value="' + p[n] + '">'; h += '<embed type="' + mt + '"'; for (n in p) h += n + '="' + p[n] + '" '; h += '></embed></object>'; document.write(h); }
JavaScript
/** * editor_plugin_src.js * * Copyright 2009, Moxiecode Systems AB * Released under LGPL License. * * License: http://tinymce.moxiecode.com/license * Contributing: http://tinymce.moxiecode.com/contributing */ (function() { var each = tinymce.each; tinymce.create('tinymce.plugins.AdvListPlugin', { init : function(ed, url) { var t = this; t.editor = ed; function buildFormats(str) { var formats = []; each(str.split(/,/), function(type) { formats.push({ title : 'advlist.' + (type == 'default' ? 'def' : type.replace(/-/g, '_')), styles : { listStyleType : type == 'default' ? '' : type } }); }); return formats; }; // Setup number formats from config or default t.numlist = ed.getParam("advlist_number_styles") || buildFormats("default,lower-alpha,lower-greek,lower-roman,upper-alpha,upper-roman"); t.bullist = ed.getParam("advlist_bullet_styles") || buildFormats("default,circle,disc,square"); }, createControl: function(name, cm) { var t = this, btn, format; if (name == 'numlist' || name == 'bullist') { // Default to first item if it's a default item if (t[name][0].title == 'advlist.def') format = t[name][0]; function hasFormat(node, format) { var state = true; each(format.styles, function(value, name) { // Format doesn't match if (t.editor.dom.getStyle(node, name) != value) { state = false; return false; } }); return state; }; function applyListFormat() { var list, ed = t.editor, dom = ed.dom, sel = ed.selection; // Check for existing list element list = dom.getParent(sel.getNode(), 'ol,ul'); // Switch/add list type if needed if (!list || list.nodeName == (name == 'bullist' ? 'OL' : 'UL') || hasFormat(list, format)) ed.execCommand(name == 'bullist' ? 'InsertUnorderedList' : 'InsertOrderedList'); // Append styles to new list element if (format) { list = dom.getParent(sel.getNode(), 'ol,ul'); if (list) { dom.setStyles(list, format.styles); list.removeAttribute('_mce_style'); } } }; btn = cm.createSplitButton(name, { title : 'advanced.' + name + '_desc', 'class' : 'mce_' + name, onclick : function() { applyListFormat(); } }); btn.onRenderMenu.add(function(btn, menu) { menu.onShowMenu.add(function() { var dom = t.editor.dom, list = dom.getParent(t.editor.selection.getNode(), 'ol,ul'), fmtList; if (list || format) { fmtList = t[name]; // Unselect existing items each(menu.items, function(item) { var state = true; item.setSelected(0); if (list && !item.isDisabled()) { each(fmtList, function(fmt) { if (fmt.id == item.id) { if (!hasFormat(list, fmt)) { state = false; return false; } } }); if (state) item.setSelected(1); } }); // Select the current format if (!list) menu.items[format.id].setSelected(1); } }); menu.add({id : t.editor.dom.uniqueId(), title : 'advlist.types', 'class' : 'mceMenuItemTitle'}).setDisabled(1); each(t[name], function(item) { item.id = t.editor.dom.uniqueId(); menu.add({id : item.id, title : item.title, onclick : function() { format = item; applyListFormat(); }}); }); }); return btn; } }, getInfo : function() { return { longname : 'Advanced lists', author : 'Moxiecode Systems AB', authorurl : 'http://tinymce.moxiecode.com', infourl : 'http://wiki.moxiecode.com/index.php/TinyMCE:Plugins/advlist', version : tinymce.majorVersion + "." + tinymce.minorVersion }; } }); // Register plugin tinymce.PluginManager.add('advlist', tinymce.plugins.AdvListPlugin); })();
JavaScript
/** * editor_plugin_src.js * * Copyright 2009, Moxiecode Systems AB * Released under LGPL License. * * License: http://tinymce.moxiecode.com/license * Contributing: http://tinymce.moxiecode.com/contributing */ (function() { tinymce.create('tinymce.plugins.Layer', { init : function(ed, url) { var t = this; t.editor = ed; // Register commands ed.addCommand('mceInsertLayer', t._insertLayer, t); ed.addCommand('mceMoveForward', function() { t._move(1); }); ed.addCommand('mceMoveBackward', function() { t._move(-1); }); ed.addCommand('mceMakeAbsolute', function() { t._toggleAbsolute(); }); // Register buttons ed.addButton('moveforward', {title : 'layer.forward_desc', cmd : 'mceMoveForward'}); ed.addButton('movebackward', {title : 'layer.backward_desc', cmd : 'mceMoveBackward'}); ed.addButton('absolute', {title : 'layer.absolute_desc', cmd : 'mceMakeAbsolute'}); ed.addButton('insertlayer', {title : 'layer.insertlayer_desc', cmd : 'mceInsertLayer'}); ed.onInit.add(function() { if (tinymce.isIE) ed.getDoc().execCommand('2D-Position', false, true); }); ed.onNodeChange.add(t._nodeChange, t); ed.onVisualAid.add(t._visualAid, t); }, getInfo : function() { return { longname : 'Layer', author : 'Moxiecode Systems AB', authorurl : 'http://tinymce.moxiecode.com', infourl : 'http://wiki.moxiecode.com/index.php/TinyMCE:Plugins/layer', version : tinymce.majorVersion + "." + tinymce.minorVersion }; }, // Private methods _nodeChange : function(ed, cm, n) { var le, p; le = this._getParentLayer(n); p = ed.dom.getParent(n, 'DIV,P,IMG'); if (!p) { cm.setDisabled('absolute', 1); cm.setDisabled('moveforward', 1); cm.setDisabled('movebackward', 1); } else { cm.setDisabled('absolute', 0); cm.setDisabled('moveforward', !le); cm.setDisabled('movebackward', !le); cm.setActive('absolute', le && le.style.position.toLowerCase() == "absolute"); } }, // Private methods _visualAid : function(ed, e, s) { var dom = ed.dom; tinymce.each(dom.select('div,p', e), function(e) { if (/^(absolute|relative|static)$/i.test(e.style.position)) { if (s) dom.addClass(e, 'mceItemVisualAid'); else dom.removeClass(e, 'mceItemVisualAid'); } }); }, _move : function(d) { var ed = this.editor, i, z = [], le = this._getParentLayer(ed.selection.getNode()), ci = -1, fi = -1, nl; nl = []; tinymce.walk(ed.getBody(), function(n) { if (n.nodeType == 1 && /^(absolute|relative|static)$/i.test(n.style.position)) nl.push(n); }, 'childNodes'); // Find z-indexes for (i=0; i<nl.length; i++) { z[i] = nl[i].style.zIndex ? parseInt(nl[i].style.zIndex) : 0; if (ci < 0 && nl[i] == le) ci = i; } if (d < 0) { // Move back // Try find a lower one for (i=0; i<z.length; i++) { if (z[i] < z[ci]) { fi = i; break; } } if (fi > -1) { nl[ci].style.zIndex = z[fi]; nl[fi].style.zIndex = z[ci]; } else { if (z[ci] > 0) nl[ci].style.zIndex = z[ci] - 1; } } else { // Move forward // Try find a higher one for (i=0; i<z.length; i++) { if (z[i] > z[ci]) { fi = i; break; } } if (fi > -1) { nl[ci].style.zIndex = z[fi]; nl[fi].style.zIndex = z[ci]; } else nl[ci].style.zIndex = z[ci] + 1; } ed.execCommand('mceRepaint'); }, _getParentLayer : function(n) { return this.editor.dom.getParent(n, function(n) { return n.nodeType == 1 && /^(absolute|relative|static)$/i.test(n.style.position); }); }, _insertLayer : function() { var ed = this.editor, p = ed.dom.getPos(ed.dom.getParent(ed.selection.getNode(), '*')); ed.dom.add(ed.getBody(), 'div', { style : { position : 'absolute', left : p.x, top : (p.y > 20 ? p.y : 20), width : 100, height : 100 }, 'class' : 'mceItemVisualAid' }, ed.selection.getContent() || ed.getLang('layer.content')); }, _toggleAbsolute : function() { var ed = this.editor, le = this._getParentLayer(ed.selection.getNode()); if (!le) le = ed.dom.getParent(ed.selection.getNode(), 'DIV,P,IMG'); if (le) { if (le.style.position.toLowerCase() == "absolute") { ed.dom.setStyles(le, { position : '', left : '', top : '', width : '', height : '' }); ed.dom.removeClass(le, 'mceItemVisualAid'); } else { if (le.style.left == "") le.style.left = 20 + 'px'; if (le.style.top == "") le.style.top = 20 + 'px'; if (le.style.width == "") le.style.width = le.width ? (le.width + 'px') : '100px'; if (le.style.height == "") le.style.height = le.height ? (le.height + 'px') : '100px'; le.style.position = "absolute"; ed.addVisual(ed.getBody()); } ed.execCommand('mceRepaint'); ed.nodeChanged(); } } }); // Register plugin tinymce.PluginManager.add('layer', tinymce.plugins.Layer); })();
JavaScript
/** * editor_plugin_src.js * * Copyright 2009, Moxiecode Systems AB * Released under LGPL License. * * License: http://tinymce.moxiecode.com/license * Contributing: http://tinymce.moxiecode.com/contributing */ (function() { tinymce.create('tinymce.plugins.IESpell', { init : function(ed, url) { var t = this, sp; if (!tinymce.isIE) return; t.editor = ed; // Register commands ed.addCommand('mceIESpell', function() { try { sp = new ActiveXObject("ieSpell.ieSpellExtension"); sp.CheckDocumentNode(ed.getDoc().documentElement); } catch (e) { if (e.number == -2146827859) { ed.windowManager.confirm(ed.getLang("iespell.download"), function(s) { if (s) window.open('http://www.iespell.com/download.php', 'ieSpellDownload', ''); }); } else ed.windowManager.alert("Error Loading ieSpell: Exception " + e.number); } }); // Register buttons ed.addButton('iespell', {title : 'iespell.iespell_desc', cmd : 'mceIESpell'}); }, getInfo : function() { return { longname : 'IESpell (IE Only)', author : 'Moxiecode Systems AB', authorurl : 'http://tinymce.moxiecode.com', infourl : 'http://wiki.moxiecode.com/index.php/TinyMCE:Plugins/iespell', version : tinymce.majorVersion + "." + tinymce.minorVersion }; } }); // Register plugin tinymce.PluginManager.add('iespell', tinymce.plugins.IESpell); })();
JavaScript
/** * editor_plugin_src.js * * Copyright 2009, Moxiecode Systems AB * Released under LGPL License. * * License: http://tinymce.moxiecode.com/license * Contributing: http://tinymce.moxiecode.com/contributing */ (function() { var DOM = tinymce.DOM, Element = tinymce.dom.Element, Event = tinymce.dom.Event, each = tinymce.each, is = tinymce.is; tinymce.create('tinymce.plugins.InlinePopups', { init : function(ed, url) { // Replace window manager ed.onBeforeRenderUI.add(function() { ed.windowManager = new tinymce.InlineWindowManager(ed); DOM.loadCSS(url + '/skins/' + (ed.settings.inlinepopups_skin || 'clearlooks2') + "/window.css"); }); }, getInfo : function() { return { longname : 'InlinePopups', author : 'Moxiecode Systems AB', authorurl : 'http://tinymce.moxiecode.com', infourl : 'http://wiki.moxiecode.com/index.php/TinyMCE:Plugins/inlinepopups', version : tinymce.majorVersion + "." + tinymce.minorVersion }; } }); tinymce.create('tinymce.InlineWindowManager:tinymce.WindowManager', { InlineWindowManager : function(ed) { var t = this; t.parent(ed); t.zIndex = 300000; t.count = 0; t.windows = {}; }, open : function(f, p) { var t = this, id, opt = '', ed = t.editor, dw = 0, dh = 0, vp, po, mdf, clf, we, w, u; f = f || {}; p = p || {}; // Run native windows if (!f.inline) return t.parent(f, p); // Only store selection if the type is a normal window if (!f.type) t.bookmark = ed.selection.getBookmark(1); id = DOM.uniqueId(); vp = DOM.getViewPort(); f.width = parseInt(f.width || 320); f.height = parseInt(f.height || 240) + (tinymce.isIE ? 8 : 0); f.min_width = parseInt(f.min_width || 150); f.min_height = parseInt(f.min_height || 100); f.max_width = parseInt(f.max_width || 2000); f.max_height = parseInt(f.max_height || 2000); f.left = f.left || Math.round(Math.max(vp.x, vp.x + (vp.w / 2.0) - (f.width / 2.0))); f.top = f.top || Math.round(Math.max(vp.y, vp.y + (vp.h / 2.0) - (f.height / 2.0))); f.movable = f.resizable = true; p.mce_width = f.width; p.mce_height = f.height; p.mce_inline = true; p.mce_window_id = id; p.mce_auto_focus = f.auto_focus; // Transpose // po = DOM.getPos(ed.getContainer()); // f.left -= po.x; // f.top -= po.y; t.features = f; t.params = p; t.onOpen.dispatch(t, f, p); if (f.type) { opt += ' mceModal'; if (f.type) opt += ' mce' + f.type.substring(0, 1).toUpperCase() + f.type.substring(1); f.resizable = false; } if (f.statusbar) opt += ' mceStatusbar'; if (f.resizable) opt += ' mceResizable'; if (f.minimizable) opt += ' mceMinimizable'; if (f.maximizable) opt += ' mceMaximizable'; if (f.movable) opt += ' mceMovable'; // Create DOM objects t._addAll(DOM.doc.body, ['div', {id : id, 'class' : ed.settings.inlinepopups_skin || 'clearlooks2', style : 'width:100px;height:100px'}, ['div', {id : id + '_wrapper', 'class' : 'mceWrapper' + opt}, ['div', {id : id + '_top', 'class' : 'mceTop'}, ['div', {'class' : 'mceLeft'}], ['div', {'class' : 'mceCenter'}], ['div', {'class' : 'mceRight'}], ['span', {id : id + '_title'}, f.title || ''] ], ['div', {id : id + '_middle', 'class' : 'mceMiddle'}, ['div', {id : id + '_left', 'class' : 'mceLeft'}], ['span', {id : id + '_content'}], ['div', {id : id + '_right', 'class' : 'mceRight'}] ], ['div', {id : id + '_bottom', 'class' : 'mceBottom'}, ['div', {'class' : 'mceLeft'}], ['div', {'class' : 'mceCenter'}], ['div', {'class' : 'mceRight'}], ['span', {id : id + '_status'}, 'Content'] ], ['a', {'class' : 'mceMove', tabindex : '-1', href : 'javascript:;'}], ['a', {'class' : 'mceMin', tabindex : '-1', href : 'javascript:;', onmousedown : 'return false;'}], ['a', {'class' : 'mceMax', tabindex : '-1', href : 'javascript:;', onmousedown : 'return false;'}], ['a', {'class' : 'mceMed', tabindex : '-1', href : 'javascript:;', onmousedown : 'return false;'}], ['a', {'class' : 'mceClose', tabindex : '-1', href : 'javascript:;', onmousedown : 'return false;'}], ['a', {id : id + '_resize_n', 'class' : 'mceResize mceResizeN', tabindex : '-1', href : 'javascript:;'}], ['a', {id : id + '_resize_s', 'class' : 'mceResize mceResizeS', tabindex : '-1', href : 'javascript:;'}], ['a', {id : id + '_resize_w', 'class' : 'mceResize mceResizeW', tabindex : '-1', href : 'javascript:;'}], ['a', {id : id + '_resize_e', 'class' : 'mceResize mceResizeE', tabindex : '-1', href : 'javascript:;'}], ['a', {id : id + '_resize_nw', 'class' : 'mceResize mceResizeNW', tabindex : '-1', href : 'javascript:;'}], ['a', {id : id + '_resize_ne', 'class' : 'mceResize mceResizeNE', tabindex : '-1', href : 'javascript:;'}], ['a', {id : id + '_resize_sw', 'class' : 'mceResize mceResizeSW', tabindex : '-1', href : 'javascript:;'}], ['a', {id : id + '_resize_se', 'class' : 'mceResize mceResizeSE', tabindex : '-1', href : 'javascript:;'}] ] ] ); DOM.setStyles(id, {top : -10000, left : -10000}); // Fix gecko rendering bug, where the editors iframe messed with window contents if (tinymce.isGecko) DOM.setStyle(id, 'overflow', 'auto'); // Measure borders if (!f.type) { dw += DOM.get(id + '_left').clientWidth; dw += DOM.get(id + '_right').clientWidth; dh += DOM.get(id + '_top').clientHeight; dh += DOM.get(id + '_bottom').clientHeight; } // Resize window DOM.setStyles(id, {top : f.top, left : f.left, width : f.width + dw, height : f.height + dh}); u = f.url || f.file; if (u) { if (tinymce.relaxedDomain) u += (u.indexOf('?') == -1 ? '?' : '&') + 'mce_rdomain=' + tinymce.relaxedDomain; u = tinymce._addVer(u); } if (!f.type) { DOM.add(id + '_content', 'iframe', {id : id + '_ifr', src : 'javascript:""', frameBorder : 0, style : 'border:0;width:10px;height:10px'}); DOM.setStyles(id + '_ifr', {width : f.width, height : f.height}); DOM.setAttrib(id + '_ifr', 'src', u); } else { DOM.add(id + '_wrapper', 'a', {id : id + '_ok', 'class' : 'mceButton mceOk', href : 'javascript:;', onmousedown : 'return false;'}, 'Ok'); if (f.type == 'confirm') DOM.add(id + '_wrapper', 'a', {'class' : 'mceButton mceCancel', href : 'javascript:;', onmousedown : 'return false;'}, 'Cancel'); DOM.add(id + '_middle', 'div', {'class' : 'mceIcon'}); DOM.setHTML(id + '_content', f.content.replace('\n', '<br />')); } // Register events mdf = Event.add(id, 'mousedown', function(e) { var n = e.target, w, vp; w = t.windows[id]; t.focus(id); if (n.nodeName == 'A' || n.nodeName == 'a') { if (n.className == 'mceMax') { w.oldPos = w.element.getXY(); w.oldSize = w.element.getSize(); vp = DOM.getViewPort(); // Reduce viewport size to avoid scrollbars vp.w -= 2; vp.h -= 2; w.element.moveTo(vp.x, vp.y); w.element.resizeTo(vp.w, vp.h); DOM.setStyles(id + '_ifr', {width : vp.w - w.deltaWidth, height : vp.h - w.deltaHeight}); DOM.addClass(id + '_wrapper', 'mceMaximized'); } else if (n.className == 'mceMed') { // Reset to old size w.element.moveTo(w.oldPos.x, w.oldPos.y); w.element.resizeTo(w.oldSize.w, w.oldSize.h); w.iframeElement.resizeTo(w.oldSize.w - w.deltaWidth, w.oldSize.h - w.deltaHeight); DOM.removeClass(id + '_wrapper', 'mceMaximized'); } else if (n.className == 'mceMove') return t._startDrag(id, e, n.className); else if (DOM.hasClass(n, 'mceResize')) return t._startDrag(id, e, n.className.substring(13)); } }); clf = Event.add(id, 'click', function(e) { var n = e.target; t.focus(id); if (n.nodeName == 'A' || n.nodeName == 'a') { switch (n.className) { case 'mceClose': t.close(null, id); return Event.cancel(e); case 'mceButton mceOk': case 'mceButton mceCancel': f.button_func(n.className == 'mceButton mceOk'); return Event.cancel(e); } } }); // Add window w = t.windows[id] = { id : id, mousedown_func : mdf, click_func : clf, element : new Element(id, {blocker : 1, container : ed.getContainer()}), iframeElement : new Element(id + '_ifr'), features : f, deltaWidth : dw, deltaHeight : dh }; w.iframeElement.on('focus', function() { t.focus(id); }); // Setup blocker if (t.count == 0 && t.editor.getParam('dialog_type', 'modal') == 'modal') { DOM.add(DOM.doc.body, 'div', { id : 'mceModalBlocker', 'class' : (t.editor.settings.inlinepopups_skin || 'clearlooks2') + '_modalBlocker', style : {zIndex : t.zIndex - 1} }); DOM.show('mceModalBlocker'); // Reduces flicker in IE } else DOM.setStyle('mceModalBlocker', 'z-index', t.zIndex - 1); if (tinymce.isIE6 || /Firefox\/2\./.test(navigator.userAgent) || (tinymce.isIE && !DOM.boxModel)) DOM.setStyles('mceModalBlocker', {position : 'absolute', left : vp.x, top : vp.y, width : vp.w - 2, height : vp.h - 2}); t.focus(id); t._fixIELayout(id, 1); // Focus ok button if (DOM.get(id + '_ok')) DOM.get(id + '_ok').focus(); t.count++; return w; }, focus : function(id) { var t = this, w; if (w = t.windows[id]) { w.zIndex = this.zIndex++; w.element.setStyle('zIndex', w.zIndex); w.element.update(); id = id + '_wrapper'; DOM.removeClass(t.lastId, 'mceFocus'); DOM.addClass(id, 'mceFocus'); t.lastId = id; } }, _addAll : function(te, ne) { var i, n, t = this, dom = tinymce.DOM; if (is(ne, 'string')) te.appendChild(dom.doc.createTextNode(ne)); else if (ne.length) { te = te.appendChild(dom.create(ne[0], ne[1])); for (i=2; i<ne.length; i++) t._addAll(te, ne[i]); } }, _startDrag : function(id, se, ac) { var t = this, mu, mm, d = DOM.doc, eb, w = t.windows[id], we = w.element, sp = we.getXY(), p, sz, ph, cp, vp, sx, sy, sex, sey, dx, dy, dw, dh; // Get positons and sizes // cp = DOM.getPos(t.editor.getContainer()); cp = {x : 0, y : 0}; vp = DOM.getViewPort(); // Reduce viewport size to avoid scrollbars while dragging vp.w -= 2; vp.h -= 2; sex = se.screenX; sey = se.screenY; dx = dy = dw = dh = 0; // Handle mouse up mu = Event.add(d, 'mouseup', function(e) { Event.remove(d, 'mouseup', mu); Event.remove(d, 'mousemove', mm); if (eb) eb.remove(); we.moveBy(dx, dy); we.resizeBy(dw, dh); sz = we.getSize(); DOM.setStyles(id + '_ifr', {width : sz.w - w.deltaWidth, height : sz.h - w.deltaHeight}); t._fixIELayout(id, 1); return Event.cancel(e); }); if (ac != 'Move') startMove(); function startMove() { if (eb) return; t._fixIELayout(id, 0); // Setup event blocker DOM.add(d.body, 'div', { id : 'mceEventBlocker', 'class' : 'mceEventBlocker ' + (t.editor.settings.inlinepopups_skin || 'clearlooks2'), style : {zIndex : t.zIndex + 1} }); if (tinymce.isIE6 || (tinymce.isIE && !DOM.boxModel)) DOM.setStyles('mceEventBlocker', {position : 'absolute', left : vp.x, top : vp.y, width : vp.w - 2, height : vp.h - 2}); eb = new Element('mceEventBlocker'); eb.update(); // Setup placeholder p = we.getXY(); sz = we.getSize(); sx = cp.x + p.x - vp.x; sy = cp.y + p.y - vp.y; DOM.add(eb.get(), 'div', {id : 'mcePlaceHolder', 'class' : 'mcePlaceHolder', style : {left : sx, top : sy, width : sz.w, height : sz.h}}); ph = new Element('mcePlaceHolder'); }; // Handle mouse move/drag mm = Event.add(d, 'mousemove', function(e) { var x, y, v; startMove(); x = e.screenX - sex; y = e.screenY - sey; switch (ac) { case 'ResizeW': dx = x; dw = 0 - x; break; case 'ResizeE': dw = x; break; case 'ResizeN': case 'ResizeNW': case 'ResizeNE': if (ac == "ResizeNW") { dx = x; dw = 0 - x; } else if (ac == "ResizeNE") dw = x; dy = y; dh = 0 - y; break; case 'ResizeS': case 'ResizeSW': case 'ResizeSE': if (ac == "ResizeSW") { dx = x; dw = 0 - x; } else if (ac == "ResizeSE") dw = x; dh = y; break; case 'mceMove': dx = x; dy = y; break; } // Boundary check if (dw < (v = w.features.min_width - sz.w)) { if (dx !== 0) dx += dw - v; dw = v; } if (dh < (v = w.features.min_height - sz.h)) { if (dy !== 0) dy += dh - v; dh = v; } dw = Math.min(dw, w.features.max_width - sz.w); dh = Math.min(dh, w.features.max_height - sz.h); dx = Math.max(dx, vp.x - (sx + vp.x)); dy = Math.max(dy, vp.y - (sy + vp.y)); dx = Math.min(dx, (vp.w + vp.x) - (sx + sz.w + vp.x)); dy = Math.min(dy, (vp.h + vp.y) - (sy + sz.h + vp.y)); // Move if needed if (dx + dy !== 0) { if (sx + dx < 0) dx = 0; if (sy + dy < 0) dy = 0; ph.moveTo(sx + dx, sy + dy); } // Resize if needed if (dw + dh !== 0) ph.resizeTo(sz.w + dw, sz.h + dh); return Event.cancel(e); }); return Event.cancel(se); }, resizeBy : function(dw, dh, id) { var w = this.windows[id]; if (w) { w.element.resizeBy(dw, dh); w.iframeElement.resizeBy(dw, dh); } }, close : function(win, id) { var t = this, w, d = DOM.doc, ix = 0, fw, id; id = t._findId(id || win); // Probably not inline if (!t.windows[id]) { t.parent(win); return; } t.count--; if (t.count == 0) DOM.remove('mceModalBlocker'); if (w = t.windows[id]) { t.onClose.dispatch(t); Event.remove(d, 'mousedown', w.mousedownFunc); Event.remove(d, 'click', w.clickFunc); Event.clear(id); Event.clear(id + '_ifr'); DOM.setAttrib(id + '_ifr', 'src', 'javascript:""'); // Prevent leak w.element.remove(); delete t.windows[id]; // Find front most window and focus that each (t.windows, function(w) { if (w.zIndex > ix) { fw = w; ix = w.zIndex; } }); if (fw) t.focus(fw.id); } }, setTitle : function(w, ti) { var e; w = this._findId(w); if (e = DOM.get(w + '_title')) e.innerHTML = DOM.encode(ti); }, alert : function(txt, cb, s) { var t = this, w; w = t.open({ title : t, type : 'alert', button_func : function(s) { if (cb) cb.call(s || t, s); t.close(null, w.id); }, content : DOM.encode(t.editor.getLang(txt, txt)), inline : 1, width : 400, height : 130 }); }, confirm : function(txt, cb, s) { var t = this, w; w = t.open({ title : t, type : 'confirm', button_func : function(s) { if (cb) cb.call(s || t, s); t.close(null, w.id); }, content : DOM.encode(t.editor.getLang(txt, txt)), inline : 1, width : 400, height : 130 }); }, // Internal functions _findId : function(w) { var t = this; if (typeof(w) == 'string') return w; each(t.windows, function(wo) { var ifr = DOM.get(wo.id + '_ifr'); if (ifr && w == ifr.contentWindow) { w = wo.id; return false; } }); return w; }, _fixIELayout : function(id, s) { var w, img; if (!tinymce.isIE6) return; // Fixes the bug where hover flickers and does odd things in IE6 each(['n','s','w','e','nw','ne','sw','se'], function(v) { var e = DOM.get(id + '_resize_' + v); DOM.setStyles(e, { width : s ? e.clientWidth : '', height : s ? e.clientHeight : '', cursor : DOM.getStyle(e, 'cursor', 1) }); DOM.setStyle(id + "_bottom", 'bottom', '-1px'); e = 0; }); // Fixes graphics glitch if (w = this.windows[id]) { // Fixes rendering bug after resize w.element.hide(); w.element.show(); // Forced a repaint of the window //DOM.get(id).style.filter = ''; // IE has a bug where images used in CSS won't get loaded // sometimes when the cache in the browser is disabled // This fix tries to solve it by loading the images using the image object each(DOM.select('div,a', id), function(e, i) { if (e.currentStyle.backgroundImage != 'none') { img = new Image(); img.src = e.currentStyle.backgroundImage.replace(/url\(\"(.+)\"\)/, '$1'); } }); DOM.get(id).style.filter = ''; } } }); // Register plugin tinymce.PluginManager.add('inlinepopups', tinymce.plugins.InlinePopups); })();
JavaScript
/** * editor_plugin_src.js * * Copyright 2009, Moxiecode Systems AB * Released under LGPL License. * * License: http://tinymce.moxiecode.com/license * Contributing: http://tinymce.moxiecode.com/contributing */ (function() { var Event = tinymce.dom.Event, each = tinymce.each, DOM = tinymce.DOM; /** * This plugin a context menu to TinyMCE editor instances. * * @class tinymce.plugins.ContextMenu */ tinymce.create('tinymce.plugins.ContextMenu', { /** * Initializes the plugin, this will be executed after the plugin has been created. * This call is done before the editor instance has finished it's initialization so use the onInit event * of the editor instance to intercept that event. * * @method init * @param {tinymce.Editor} ed Editor instance that the plugin is initialized in. * @param {string} url Absolute URL to where the plugin is located. */ init : function(ed) { var t = this, lastRng; t.editor = ed; /** * This event gets fired when the context menu is shown. * * @event onContextMenu * @param {tinymce.plugins.ContextMenu} sender Plugin instance sending the event. * @param {tinymce.ui.DropMenu} menu Drop down menu to fill with more items if needed. */ t.onContextMenu = new tinymce.util.Dispatcher(this); ed.onContextMenu.add(function(ed, e) { if (!e.ctrlKey) { // Restore the last selection since it was removed if (lastRng) ed.selection.setRng(lastRng); t._getMenu(ed).showMenu(e.clientX, e.clientY); Event.add(ed.getDoc(), 'click', function(e) { hide(ed, e); }); Event.cancel(e); } }); ed.onRemove.add(function() { if (t._menu) t._menu.removeAll(); }); function hide(ed, e) { lastRng = null; // Since the contextmenu event moves // the selection we need to store it away if (e && e.button == 2) { lastRng = ed.selection.getRng(); return; } if (t._menu) { t._menu.removeAll(); t._menu.destroy(); Event.remove(ed.getDoc(), 'click', hide); } }; ed.onMouseDown.add(hide); ed.onKeyDown.add(hide); }, /** * Returns information about the plugin as a name/value array. * The current keys are longname, author, authorurl, infourl and version. * * @method getInfo * @return {Object} Name/value array containing information about the plugin. */ getInfo : function() { return { longname : 'Contextmenu', author : 'Moxiecode Systems AB', authorurl : 'http://tinymce.moxiecode.com', infourl : 'http://wiki.moxiecode.com/index.php/TinyMCE:Plugins/contextmenu', version : tinymce.majorVersion + "." + tinymce.minorVersion }; }, _getMenu : function(ed) { var t = this, m = t._menu, se = ed.selection, col = se.isCollapsed(), el = se.getNode() || ed.getBody(), am, p1, p2; if (m) { m.removeAll(); m.destroy(); } p1 = DOM.getPos(ed.getContentAreaContainer()); p2 = DOM.getPos(ed.getContainer()); m = ed.controlManager.createDropMenu('contextmenu', { offset_x : p1.x + ed.getParam('contextmenu_offset_x', 0), offset_y : p1.y + ed.getParam('contextmenu_offset_y', 0), constrain : 1 }); t._menu = m; m.add({title : 'advanced.cut_desc', icon : 'cut', cmd : 'Cut'}).setDisabled(col); m.add({title : 'advanced.copy_desc', icon : 'copy', cmd : 'Copy'}).setDisabled(col); m.add({title : 'advanced.paste_desc', icon : 'paste', cmd : 'Paste'}); if ((el.nodeName == 'A' && !ed.dom.getAttrib(el, 'name')) || !col) { m.addSeparator(); m.add({title : 'advanced.link_desc', icon : 'link', cmd : ed.plugins.advlink ? 'mceAdvLink' : 'mceLink', ui : true}); m.add({title : 'advanced.unlink_desc', icon : 'unlink', cmd : 'UnLink'}); } m.addSeparator(); m.add({title : 'advanced.image_desc', icon : 'image', cmd : ed.plugins.advimage ? 'mceAdvImage' : 'mceImage', ui : true}); m.addSeparator(); am = m.addMenu({title : 'contextmenu.align'}); am.add({title : 'contextmenu.left', icon : 'justifyleft', cmd : 'JustifyLeft'}); am.add({title : 'contextmenu.center', icon : 'justifycenter', cmd : 'JustifyCenter'}); am.add({title : 'contextmenu.right', icon : 'justifyright', cmd : 'JustifyRight'}); am.add({title : 'contextmenu.full', icon : 'justifyfull', cmd : 'JustifyFull'}); t.onContextMenu.dispatch(t, m, el, col); return m; } }); // Register plugin tinymce.PluginManager.add('contextmenu', tinymce.plugins.ContextMenu); })();
JavaScript
tinyMCEPopup.requireLangPack(); var oldWidth, oldHeight, ed, url; if (url = tinyMCEPopup.getParam("media_external_list_url")) document.write('<script language="javascript" type="text/javascript" src="' + tinyMCEPopup.editor.documentBaseURI.toAbsolute(url) + '"></script>'); function init() { var pl = "", f, val; var type = "flash", fe, i; ed = tinyMCEPopup.editor; tinyMCEPopup.resizeToInnerSize(); f = document.forms[0] fe = ed.selection.getNode(); if (/mceItem(Flash|ShockWave|WindowsMedia|QuickTime|RealMedia)/.test(ed.dom.getAttrib(fe, 'class'))) { pl = fe.title; switch (ed.dom.getAttrib(fe, 'class')) { case 'mceItemFlash': type = 'flash'; break; case 'mceItemFlashVideo': type = 'flv'; break; case 'mceItemShockWave': type = 'shockwave'; break; case 'mceItemWindowsMedia': type = 'wmp'; break; case 'mceItemQuickTime': type = 'qt'; break; case 'mceItemRealMedia': type = 'rmp'; break; } document.forms[0].insert.value = ed.getLang('update', 'Insert', true); } document.getElementById('filebrowsercontainer').innerHTML = getBrowserHTML('filebrowser','src','media','media'); document.getElementById('qtsrcfilebrowsercontainer').innerHTML = getBrowserHTML('qtsrcfilebrowser','qt_qtsrc','media','media'); document.getElementById('bgcolor_pickcontainer').innerHTML = getColorPickerHTML('bgcolor_pick','bgcolor'); var html = getMediaListHTML('medialist','src','media','media'); if (html == "") document.getElementById("linklistrow").style.display = 'none'; else document.getElementById("linklistcontainer").innerHTML = html; // Resize some elements if (isVisible('filebrowser')) document.getElementById('src').style.width = '230px'; // Setup form if (pl != "") { pl = tinyMCEPopup.editor.plugins.media._parse(pl); switch (type) { case "flash": setBool(pl, 'flash', 'play'); setBool(pl, 'flash', 'loop'); setBool(pl, 'flash', 'menu'); setBool(pl, 'flash', 'swliveconnect'); setStr(pl, 'flash', 'quality'); setStr(pl, 'flash', 'scale'); setStr(pl, 'flash', 'salign'); setStr(pl, 'flash', 'wmode'); setStr(pl, 'flash', 'base'); setStr(pl, 'flash', 'flashvars'); break; case "qt": setBool(pl, 'qt', 'loop'); setBool(pl, 'qt', 'autoplay'); setBool(pl, 'qt', 'cache'); setBool(pl, 'qt', 'controller'); setBool(pl, 'qt', 'correction'); setBool(pl, 'qt', 'enablejavascript'); setBool(pl, 'qt', 'kioskmode'); setBool(pl, 'qt', 'autohref'); setBool(pl, 'qt', 'playeveryframe'); setBool(pl, 'qt', 'tarsetcache'); setStr(pl, 'qt', 'scale'); setStr(pl, 'qt', 'starttime'); setStr(pl, 'qt', 'endtime'); setStr(pl, 'qt', 'tarset'); setStr(pl, 'qt', 'qtsrcchokespeed'); setStr(pl, 'qt', 'volume'); setStr(pl, 'qt', 'qtsrc'); break; case "shockwave": setBool(pl, 'shockwave', 'sound'); setBool(pl, 'shockwave', 'progress'); setBool(pl, 'shockwave', 'autostart'); setBool(pl, 'shockwave', 'swliveconnect'); setStr(pl, 'shockwave', 'swvolume'); setStr(pl, 'shockwave', 'swstretchstyle'); setStr(pl, 'shockwave', 'swstretchhalign'); setStr(pl, 'shockwave', 'swstretchvalign'); break; case "wmp": setBool(pl, 'wmp', 'autostart'); setBool(pl, 'wmp', 'enabled'); setBool(pl, 'wmp', 'enablecontextmenu'); setBool(pl, 'wmp', 'fullscreen'); setBool(pl, 'wmp', 'invokeurls'); setBool(pl, 'wmp', 'mute'); setBool(pl, 'wmp', 'stretchtofit'); setBool(pl, 'wmp', 'windowlessvideo'); setStr(pl, 'wmp', 'balance'); setStr(pl, 'wmp', 'baseurl'); setStr(pl, 'wmp', 'captioningid'); setStr(pl, 'wmp', 'currentmarker'); setStr(pl, 'wmp', 'currentposition'); setStr(pl, 'wmp', 'defaultframe'); setStr(pl, 'wmp', 'playcount'); setStr(pl, 'wmp', 'rate'); setStr(pl, 'wmp', 'uimode'); setStr(pl, 'wmp', 'volume'); break; case "rmp": setBool(pl, 'rmp', 'autostart'); setBool(pl, 'rmp', 'loop'); setBool(pl, 'rmp', 'autogotourl'); setBool(pl, 'rmp', 'center'); setBool(pl, 'rmp', 'imagestatus'); setBool(pl, 'rmp', 'maintainaspect'); setBool(pl, 'rmp', 'nojava'); setBool(pl, 'rmp', 'prefetch'); setBool(pl, 'rmp', 'shuffle'); setStr(pl, 'rmp', 'console'); setStr(pl, 'rmp', 'controls'); setStr(pl, 'rmp', 'numloop'); setStr(pl, 'rmp', 'scriptcallbacks'); break; } setStr(pl, null, 'src'); setStr(pl, null, 'id'); setStr(pl, null, 'name'); setStr(pl, null, 'vspace'); setStr(pl, null, 'hspace'); setStr(pl, null, 'bgcolor'); setStr(pl, null, 'align'); setStr(pl, null, 'width'); setStr(pl, null, 'height'); if ((val = ed.dom.getAttrib(fe, "width")) != "") pl.width = f.width.value = val; if ((val = ed.dom.getAttrib(fe, "height")) != "") pl.height = f.height.value = val; oldWidth = pl.width ? parseInt(pl.width) : 0; oldHeight = pl.height ? parseInt(pl.height) : 0; } else oldWidth = oldHeight = 0; selectByValue(f, 'media_type', type); changedType(type); updateColor('bgcolor_pick', 'bgcolor'); TinyMCE_EditableSelects.init(); generatePreview(); } function insertMedia() { var fe, f = document.forms[0], h; tinyMCEPopup.restoreSelection(); if (!AutoValidator.validate(f)) { tinyMCEPopup.alert(ed.getLang('invalid_data')); return false; } f.width.value = f.width.value == "" ? 100 : f.width.value; f.height.value = f.height.value == "" ? 100 : f.height.value; fe = ed.selection.getNode(); if (fe != null && /mceItem(Flash|ShockWave|WindowsMedia|QuickTime|RealMedia)/.test(ed.dom.getAttrib(fe, 'class'))) { switch (f.media_type.options[f.media_type.selectedIndex].value) { case "flash": fe.className = "mceItemFlash"; break; case "flv": fe.className = "mceItemFlashVideo"; break; case "shockwave": fe.className = "mceItemShockWave"; break; case "qt": fe.className = "mceItemQuickTime"; break; case "wmp": fe.className = "mceItemWindowsMedia"; break; case "rmp": fe.className = "mceItemRealMedia"; break; } if (fe.width != f.width.value || fe.height != f.height.value) ed.execCommand('mceRepaint'); fe.title = serializeParameters(); fe.width = f.width.value; fe.height = f.height.value; fe.style.width = f.width.value + (f.width.value.indexOf('%') == -1 ? 'px' : ''); fe.style.height = f.height.value + (f.height.value.indexOf('%') == -1 ? 'px' : ''); fe.align = f.align.options[f.align.selectedIndex].value; } else { h = '<img src="' + tinyMCEPopup.getWindowArg("plugin_url") + '/img/trans.gif"' ; switch (f.media_type.options[f.media_type.selectedIndex].value) { case "flash": h += ' class="mceItemFlash"'; break; case "flv": h += ' class="mceItemFlashVideo"'; break; case "shockwave": h += ' class="mceItemShockWave"'; break; case "qt": h += ' class="mceItemQuickTime"'; break; case "wmp": h += ' class="mceItemWindowsMedia"'; break; case "rmp": h += ' class="mceItemRealMedia"'; break; } h += ' title="' + serializeParameters() + '"'; h += ' width="' + f.width.value + '"'; h += ' height="' + f.height.value + '"'; h += ' align="' + f.align.options[f.align.selectedIndex].value + '"'; h += ' />'; ed.execCommand('mceInsertContent', false, h); } tinyMCEPopup.close(); } function updatePreview() { var f = document.forms[0], type; f.width.value = f.width.value || '320'; f.height.value = f.height.value || '240'; type = getType(f.src.value); selectByValue(f, 'media_type', type); changedType(type); generatePreview(); } function getMediaListHTML() { if (typeof(tinyMCEMediaList) != "undefined" && tinyMCEMediaList.length > 0) { var html = ""; html += '<select id="linklist" name="linklist" style="width: 250px" onchange="this.form.src.value=this.options[this.selectedIndex].value;updatePreview();">'; html += '<option value="">---</option>'; for (var i=0; i<tinyMCEMediaList.length; i++) html += '<option value="' + tinyMCEMediaList[i][1] + '">' + tinyMCEMediaList[i][0] + '</option>'; html += '</select>'; return html; } return ""; } function getType(v) { var fo, i, c, el, x, f = document.forms[0]; fo = ed.getParam("media_types", "flash=swf;flv=flv;shockwave=dcr;qt=mov,qt,mpg,mp3,mp4,mpeg;shockwave=dcr;wmp=avi,wmv,wm,asf,asx,wmx,wvx;rmp=rm,ra,ram").split(';'); // YouTube if (v.match(/watch\?v=(.+)(.*)/)) { f.width.value = '425'; f.height.value = '350'; f.src.value = 'http://www.youtube.com/v/' + v.match(/v=(.*)(.*)/)[0].split('=')[1]; return 'flash'; } // Google video if (v.indexOf('http://video.google.com/videoplay?docid=') == 0) { f.width.value = '425'; f.height.value = '326'; f.src.value = 'http://video.google.com/googleplayer.swf?docId=' + v.substring('http://video.google.com/videoplay?docid='.length) + '&hl=en'; return 'flash'; } for (i=0; i<fo.length; i++) { c = fo[i].split('='); el = c[1].split(','); for (x=0; x<el.length; x++) if (v.indexOf('.' + el[x]) != -1) return c[0]; } return null; } function switchType(v) { var t = getType(v), d = document, f = d.forms[0]; if (!t) return; selectByValue(d.forms[0], 'media_type', t); changedType(t); // Update qtsrc also if (t == 'qt' && f.src.value.toLowerCase().indexOf('rtsp://') != -1) { alert(ed.getLang("media_qt_stream_warn")); if (f.qt_qtsrc.value == '') f.qt_qtsrc.value = f.src.value; } } function changedType(t) { var d = document; d.getElementById('flash_options').style.display = 'none'; d.getElementById('flv_options').style.display = 'none'; d.getElementById('qt_options').style.display = 'none'; d.getElementById('shockwave_options').style.display = 'none'; d.getElementById('wmp_options').style.display = 'none'; d.getElementById('rmp_options').style.display = 'none'; if (t) d.getElementById(t + '_options').style.display = 'block'; } function serializeParameters() { var d = document, f = d.forms[0], s = ''; switch (f.media_type.options[f.media_type.selectedIndex].value) { case "flash": s += getBool('flash', 'play', true); s += getBool('flash', 'loop', true); s += getBool('flash', 'menu', true); s += getBool('flash', 'swliveconnect', false); s += getStr('flash', 'quality'); s += getStr('flash', 'scale'); s += getStr('flash', 'salign'); s += getStr('flash', 'wmode'); s += getStr('flash', 'base'); s += getStr('flash', 'flashvars'); break; case "qt": s += getBool('qt', 'loop', false); s += getBool('qt', 'autoplay', true); s += getBool('qt', 'cache', false); s += getBool('qt', 'controller', true); s += getBool('qt', 'correction', false, 'none', 'full'); s += getBool('qt', 'enablejavascript', false); s += getBool('qt', 'kioskmode', false); s += getBool('qt', 'autohref', false); s += getBool('qt', 'playeveryframe', false); s += getBool('qt', 'targetcache', false); s += getStr('qt', 'scale'); s += getStr('qt', 'starttime'); s += getStr('qt', 'endtime'); s += getStr('qt', 'target'); s += getStr('qt', 'qtsrcchokespeed'); s += getStr('qt', 'volume'); s += getStr('qt', 'qtsrc'); break; case "shockwave": s += getBool('shockwave', 'sound'); s += getBool('shockwave', 'progress'); s += getBool('shockwave', 'autostart'); s += getBool('shockwave', 'swliveconnect'); s += getStr('shockwave', 'swvolume'); s += getStr('shockwave', 'swstretchstyle'); s += getStr('shockwave', 'swstretchhalign'); s += getStr('shockwave', 'swstretchvalign'); break; case "wmp": s += getBool('wmp', 'autostart', true); s += getBool('wmp', 'enabled', false); s += getBool('wmp', 'enablecontextmenu', true); s += getBool('wmp', 'fullscreen', false); s += getBool('wmp', 'invokeurls', true); s += getBool('wmp', 'mute', false); s += getBool('wmp', 'stretchtofit', false); s += getBool('wmp', 'windowlessvideo', false); s += getStr('wmp', 'balance'); s += getStr('wmp', 'baseurl'); s += getStr('wmp', 'captioningid'); s += getStr('wmp', 'currentmarker'); s += getStr('wmp', 'currentposition'); s += getStr('wmp', 'defaultframe'); s += getStr('wmp', 'playcount'); s += getStr('wmp', 'rate'); s += getStr('wmp', 'uimode'); s += getStr('wmp', 'volume'); break; case "rmp": s += getBool('rmp', 'autostart', false); s += getBool('rmp', 'loop', false); s += getBool('rmp', 'autogotourl', true); s += getBool('rmp', 'center', false); s += getBool('rmp', 'imagestatus', true); s += getBool('rmp', 'maintainaspect', false); s += getBool('rmp', 'nojava', false); s += getBool('rmp', 'prefetch', false); s += getBool('rmp', 'shuffle', false); s += getStr('rmp', 'console'); s += getStr('rmp', 'controls'); s += getStr('rmp', 'numloop'); s += getStr('rmp', 'scriptcallbacks'); break; } s += getStr(null, 'id'); s += getStr(null, 'name'); s += getStr(null, 'src'); s += getStr(null, 'align'); s += getStr(null, 'bgcolor'); s += getInt(null, 'vspace'); s += getInt(null, 'hspace'); s += getStr(null, 'width'); s += getStr(null, 'height'); s = s.length > 0 ? s.substring(0, s.length - 1) : s; return s; } function setBool(pl, p, n) { if (typeof(pl[n]) == "undefined") return; document.forms[0].elements[p + "_" + n].checked = pl[n] != 'false'; } function setStr(pl, p, n) { var f = document.forms[0], e = f.elements[(p != null ? p + "_" : '') + n]; if (typeof(pl[n]) == "undefined") return; if (e.type == "text") e.value = pl[n]; else selectByValue(f, (p != null ? p + "_" : '') + n, pl[n]); } function getBool(p, n, d, tv, fv) { var v = document.forms[0].elements[p + "_" + n].checked; tv = typeof(tv) == 'undefined' ? 'true' : "'" + jsEncode(tv) + "'"; fv = typeof(fv) == 'undefined' ? 'false' : "'" + jsEncode(fv) + "'"; return (v == d) ? '' : n + (v ? ':' + tv + ',' : ":\'" + fv + "\',"); } function getStr(p, n, d) { var e = document.forms[0].elements[(p != null ? p + "_" : "") + n]; var v = e.type == "text" ? e.value : e.options[e.selectedIndex].value; if (n == 'src') v = tinyMCEPopup.editor.convertURL(v, 'src', null); return ((n == d || v == '') ? '' : n + ":'" + jsEncode(v) + "',"); } function getInt(p, n, d) { var e = document.forms[0].elements[(p != null ? p + "_" : "") + n]; var v = e.type == "text" ? e.value : e.options[e.selectedIndex].value; return ((n == d || v == '') ? '' : n + ":" + v.replace(/[^0-9]+/g, '') + ","); } function jsEncode(s) { s = s.replace(new RegExp('\\\\', 'g'), '\\\\'); s = s.replace(new RegExp('"', 'g'), '\\"'); s = s.replace(new RegExp("'", 'g'), "\\'"); return s; } function generatePreview(c) { var f = document.forms[0], p = document.getElementById('prev'), h = '', cls, pl, n, type, codebase, wp, hp, nw, nh; p.innerHTML = '<!-- x --->'; nw = parseInt(f.width.value); nh = parseInt(f.height.value); if (f.width.value != "" && f.height.value != "") { if (f.constrain.checked) { if (c == 'width' && oldWidth != 0) { wp = nw / oldWidth; nh = Math.round(wp * nh); f.height.value = nh; } else if (c == 'height' && oldHeight != 0) { hp = nh / oldHeight; nw = Math.round(hp * nw); f.width.value = nw; } } } if (f.width.value != "") oldWidth = nw; if (f.height.value != "") oldHeight = nh; // After constrain pl = serializeParameters(); switch (f.media_type.options[f.media_type.selectedIndex].value) { case "flash": cls = 'clsid:D27CDB6E-AE6D-11cf-96B8-444553540000'; codebase = 'http://download.macromedia.com/pub/shockwave/cabs/flash/swflash.cab#version=6,0,40,0'; type = 'application/x-shockwave-flash'; break; case "shockwave": cls = 'clsid:166B1BCA-3F9C-11CF-8075-444553540000'; codebase = 'http://download.macromedia.com/pub/shockwave/cabs/director/sw.cab#version=8,5,1,0'; type = 'application/x-director'; break; case "qt": cls = 'clsid:02BF25D5-8C17-4B23-BC80-D3488ABDDC6B'; codebase = 'http://www.apple.com/qtactivex/qtplugin.cab#version=6,0,2,0'; type = 'video/quicktime'; break; case "wmp": cls = ed.getParam('media_wmp6_compatible') ? 'clsid:05589FA1-C356-11CE-BF01-00AA0055595A' : 'clsid:6BF52A52-394A-11D3-B153-00C04F79FAA6'; codebase = 'http://activex.microsoft.com/activex/controls/mplayer/en/nsmp2inf.cab#Version=5,1,52,701'; type = 'application/x-mplayer2'; break; case "rmp": cls = 'clsid:CFCDAA03-8BE4-11cf-B84B-0020AFBBCCFA'; codebase = 'http://activex.microsoft.com/activex/controls/mplayer/en/nsmp2inf.cab#Version=5,1,52,701'; type = 'audio/x-pn-realaudio-plugin'; break; } if (pl == '') { p.innerHTML = ''; return; } pl = tinyMCEPopup.editor.plugins.media._parse(pl); if (!pl.src) { p.innerHTML = ''; return; } pl.src = tinyMCEPopup.editor.documentBaseURI.toAbsolute(pl.src); pl.width = !pl.width ? 100 : pl.width; pl.height = !pl.height ? 100 : pl.height; pl.id = !pl.id ? 'obj' : pl.id; pl.name = !pl.name ? 'eobj' : pl.name; pl.align = !pl.align ? '' : pl.align; // Avoid annoying warning about insecure items if (!tinymce.isIE || document.location.protocol != 'https:') { h += '<object classid="' + cls + '" codebase="' + codebase + '" width="' + pl.width + '" height="' + pl.height + '" id="' + pl.id + '" name="' + pl.name + '" align="' + pl.align + '">'; for (n in pl) { h += '<param name="' + n + '" value="' + pl[n] + '">'; // Add extra url parameter if it's an absolute URL if (n == 'src' && pl[n].indexOf('://') != -1) h += '<param name="url" value="' + pl[n] + '" />'; } } h += '<embed type="' + type + '" '; for (n in pl) h += n + '="' + pl[n] + '" '; h += '></embed>'; // Avoid annoying warning about insecure items if (!tinymce.isIE || document.location.protocol != 'https:') h += '</object>'; p.innerHTML = "<!-- x --->" + h; } tinyMCEPopup.onInit.add(init);
JavaScript
/** * This script contains embed functions for common plugins. This scripts are complety free to use for any purpose. */ function writeFlash(p) { writeEmbed( 'D27CDB6E-AE6D-11cf-96B8-444553540000', 'http://download.macromedia.com/pub/shockwave/cabs/flash/swflash.cab#version=6,0,40,0', 'application/x-shockwave-flash', p ); } function writeShockWave(p) { writeEmbed( '166B1BCA-3F9C-11CF-8075-444553540000', 'http://download.macromedia.com/pub/shockwave/cabs/director/sw.cab#version=8,5,1,0', 'application/x-director', p ); } function writeQuickTime(p) { writeEmbed( '02BF25D5-8C17-4B23-BC80-D3488ABDDC6B', 'http://www.apple.com/qtactivex/qtplugin.cab#version=6,0,2,0', 'video/quicktime', p ); } function writeRealMedia(p) { writeEmbed( 'CFCDAA03-8BE4-11cf-B84B-0020AFBBCCFA', 'http://download.macromedia.com/pub/shockwave/cabs/flash/swflash.cab#version=6,0,40,0', 'audio/x-pn-realaudio-plugin', p ); } function writeWindowsMedia(p) { p.url = p.src; writeEmbed( '6BF52A52-394A-11D3-B153-00C04F79FAA6', 'http://activex.microsoft.com/activex/controls/mplayer/en/nsmp2inf.cab#Version=5,1,52,701', 'application/x-mplayer2', p ); } function writeEmbed(cls, cb, mt, p) { var h = '', n; h += '<object classid="clsid:' + cls + '" codebase="' + cb + '"'; h += typeof(p.id) != "undefined" ? 'id="' + p.id + '"' : ''; h += typeof(p.name) != "undefined" ? 'name="' + p.name + '"' : ''; h += typeof(p.width) != "undefined" ? 'width="' + p.width + '"' : ''; h += typeof(p.height) != "undefined" ? 'height="' + p.height + '"' : ''; h += typeof(p.align) != "undefined" ? 'align="' + p.align + '"' : ''; h += '>'; for (n in p) h += '<param name="' + n + '" value="' + p[n] + '">'; h += '<embed type="' + mt + '"'; for (n in p) h += n + '="' + p[n] + '" '; h += '></embed></object>'; document.write(h); }
JavaScript
tinyMCE.addI18n('en.media_dlg',{ title:"Insert / edit embedded media", general:"General", advanced:"Advanced", file:"File/URL", list:"List", size:"Dimensions", preview:"Preview", constrain_proportions:"Constrain proportions", type:"Type", id:"Id", name:"Name", class_name:"Class", vspace:"V-Space", hspace:"H-Space", play:"Auto play", loop:"Loop", menu:"Show menu", quality:"Quality", scale:"Scale", align:"Align", salign:"SAlign", wmode:"WMode", bgcolor:"Background", base:"Base", flashvars:"Flashvars", liveconnect:"SWLiveConnect", autohref:"AutoHREF", cache:"Cache", hidden:"Hidden", controller:"Controller", kioskmode:"Kiosk mode", playeveryframe:"Play every frame", targetcache:"Target cache", correction:"No correction", enablejavascript:"Enable JavaScript", starttime:"Start time", endtime:"End time", href:"Href", qtsrcchokespeed:"Choke speed", target:"Target", volume:"Volume", autostart:"Auto start", enabled:"Enabled", fullscreen:"Fullscreen", invokeurls:"Invoke URLs", mute:"Mute", stretchtofit:"Stretch to fit", windowlessvideo:"Windowless video", balance:"Balance", baseurl:"Base URL", captioningid:"Captioning id", currentmarker:"Current marker", currentposition:"Current position", defaultframe:"Default frame", playcount:"Play count", rate:"Rate", uimode:"UI Mode", flash_options:"Flash options", qt_options:"Quicktime options", wmp_options:"Windows media player options", rmp_options:"Real media player options", shockwave_options:"Shockwave options", autogotourl:"Auto goto URL", center:"Center", imagestatus:"Image status", maintainaspect:"Maintain aspect", nojava:"No java", prefetch:"Prefetch", shuffle:"Shuffle", console:"Console", numloop:"Num loops", controls:"Controls", scriptcallbacks:"Script callbacks", swstretchstyle:"Stretch style", swstretchhalign:"Stretch H-Align", swstretchvalign:"Stretch V-Align", sound:"Sound", progress:"Progress", qtsrc:"QT Src", qt_stream_warn:"Streamed rtsp resources should be added to the QT Src field under the advanced tab.\nYou should also add a non streamed version to the Src field..", align_top:"Top", align_right:"Right", align_bottom:"Bottom", align_left:"Left", align_center:"Center", align_top_left:"Top left", align_top_right:"Top right", align_bottom_left:"Bottom left", align_bottom_right:"Bottom right", flv_options:"Flash video options", flv_scalemode:"Scale mode", flv_buffer:"Buffer", flv_startimage:"Start image", flv_starttime:"Start time", flv_defaultvolume:"Default volumne", flv_hiddengui:"Hidden GUI", flv_autostart:"Auto start", flv_loop:"Loop", flv_showscalemodes:"Show scale modes", flv_smoothvideo:"Smooth video", flv_jscallback:"JS Callback" });
JavaScript
/** * editor_plugin_src.js * * Copyright 2009, Moxiecode Systems AB * Released under LGPL License. * * License: http://tinymce.moxiecode.com/license * Contributing: http://tinymce.moxiecode.com/contributing */ (function() { var each = tinymce.each; tinymce.create('tinymce.plugins.MediaPlugin', { init : function(ed, url) { var t = this; t.editor = ed; t.url = url; function isMediaElm(n) { return /^(mceItemFlash|mceItemShockWave|mceItemWindowsMedia|mceItemQuickTime|mceItemRealMedia)$/.test(n.className); }; ed.onPreInit.add(function() { // Force in _value parameter this extra parameter is required for older Opera versions ed.serializer.addRules('param[name|value|_mce_value]'); }); // Register commands ed.addCommand('mceMedia', function() { ed.windowManager.open({ file : url + '/media.htm', width : 430 + parseInt(ed.getLang('media.delta_width', 0)), height : 470 + parseInt(ed.getLang('media.delta_height', 0)), inline : 1 }, { plugin_url : url }); }); // Register buttons ed.addButton('media', {title : 'media.desc', cmd : 'mceMedia'}); ed.onNodeChange.add(function(ed, cm, n) { cm.setActive('media', n.nodeName == 'IMG' && isMediaElm(n)); }); ed.onInit.add(function() { var lo = { mceItemFlash : 'flash', mceItemShockWave : 'shockwave', mceItemWindowsMedia : 'windowsmedia', mceItemQuickTime : 'quicktime', mceItemRealMedia : 'realmedia' }; ed.selection.onSetContent.add(function() { t._spansToImgs(ed.getBody()); }); ed.selection.onBeforeSetContent.add(t._objectsToSpans, t); if (ed.settings.content_css !== false) ed.dom.loadCSS(url + "/css/content.css"); if (ed.theme && ed.theme.onResolveName) { ed.theme.onResolveName.add(function(th, o) { if (o.name == 'img') { each(lo, function(v, k) { if (ed.dom.hasClass(o.node, k)) { o.name = v; o.title = ed.dom.getAttrib(o.node, 'title'); return false; } }); } }); } if (ed && ed.plugins.contextmenu) { ed.plugins.contextmenu.onContextMenu.add(function(th, m, e) { if (e.nodeName == 'IMG' && /mceItem(Flash|ShockWave|WindowsMedia|QuickTime|RealMedia)/.test(e.className)) { m.add({title : 'media.edit', icon : 'media', cmd : 'mceMedia'}); } }); } }); ed.onBeforeSetContent.add(t._objectsToSpans, t); ed.onSetContent.add(function() { t._spansToImgs(ed.getBody()); }); ed.onPreProcess.add(function(ed, o) { var dom = ed.dom; if (o.set) { t._spansToImgs(o.node); each(dom.select('IMG', o.node), function(n) { var p; if (isMediaElm(n)) { p = t._parse(n.title); dom.setAttrib(n, 'width', dom.getAttrib(n, 'width', p.width || 100)); dom.setAttrib(n, 'height', dom.getAttrib(n, 'height', p.height || 100)); } }); } if (o.get) { each(dom.select('IMG', o.node), function(n) { var ci, cb, mt; if (ed.getParam('media_use_script')) { if (isMediaElm(n)) n.className = n.className.replace(/mceItem/g, 'mceTemp'); return; } switch (n.className) { case 'mceItemFlash': ci = 'd27cdb6e-ae6d-11cf-96b8-444553540000'; cb = 'http://download.macromedia.com/pub/shockwave/cabs/flash/swflash.cab#version=6,0,40,0'; mt = 'application/x-shockwave-flash'; break; case 'mceItemShockWave': ci = '166b1bca-3f9c-11cf-8075-444553540000'; cb = 'http://download.macromedia.com/pub/shockwave/cabs/director/sw.cab#version=8,5,1,0'; mt = 'application/x-director'; break; case 'mceItemWindowsMedia': ci = ed.getParam('media_wmp6_compatible') ? '05589fa1-c356-11ce-bf01-00aa0055595a' : '6bf52a52-394a-11d3-b153-00c04f79faa6'; cb = 'http://activex.microsoft.com/activex/controls/mplayer/en/nsmp2inf.cab#Version=5,1,52,701'; mt = 'application/x-mplayer2'; break; case 'mceItemQuickTime': ci = '02bf25d5-8c17-4b23-bc80-d3488abddc6b'; cb = 'http://www.apple.com/qtactivex/qtplugin.cab#version=6,0,2,0'; mt = 'video/quicktime'; break; case 'mceItemRealMedia': ci = 'cfcdaa03-8be4-11cf-b84b-0020afbbccfa'; cb = 'http://download.macromedia.com/pub/shockwave/cabs/flash/swflash.cab#version=6,0,40,0'; mt = 'audio/x-pn-realaudio-plugin'; break; } if (ci) { dom.replace(t._buildObj({ classid : ci, codebase : cb, type : mt }, n), n); } }); } }); ed.onPostProcess.add(function(ed, o) { o.content = o.content.replace(/_mce_value=/g, 'value='); }); function getAttr(s, n) { n = new RegExp(n + '=\"([^\"]+)\"', 'g').exec(s); return n ? ed.dom.decode(n[1]) : ''; }; ed.onPostProcess.add(function(ed, o) { if (ed.getParam('media_use_script')) { o.content = o.content.replace(/<img[^>]+>/g, function(im) { var cl = getAttr(im, 'class'); if (/^(mceTempFlash|mceTempShockWave|mceTempWindowsMedia|mceTempQuickTime|mceTempRealMedia)$/.test(cl)) { at = t._parse(getAttr(im, 'title')); at.width = getAttr(im, 'width'); at.height = getAttr(im, 'height'); im = '<script type="text/javascript">write' + cl.substring(7) + '({' + t._serialize(at) + '});</script>'; } return im; }); } }); }, getInfo : function() { return { longname : 'Media', author : 'Moxiecode Systems AB', authorurl : 'http://tinymce.moxiecode.com', infourl : 'http://wiki.moxiecode.com/index.php/TinyMCE:Plugins/media', version : tinymce.majorVersion + "." + tinymce.minorVersion }; }, // Private methods _objectsToSpans : function(ed, o) { var t = this, h = o.content; h = h.replace(/<script[^>]*>\s*write(Flash|ShockWave|WindowsMedia|QuickTime|RealMedia)\(\{([^\)]*)\}\);\s*<\/script>/gi, function(a, b, c) { var o = t._parse(c); return '<img class="mceItem' + b + '" title="' + ed.dom.encode(c) + '" src="' + t.url + '/img/trans.gif" width="' + o.width + '" height="' + o.height + '" />' }); h = h.replace(/<object([^>]*)>/gi, '<span class="mceItemObject" $1>'); h = h.replace(/<embed([^>]*)\/?>/gi, '<span class="mceItemEmbed" $1></span>'); h = h.replace(/<embed([^>]*)>/gi, '<span class="mceItemEmbed" $1>'); h = h.replace(/<\/(object)([^>]*)>/gi, '</span>'); h = h.replace(/<\/embed>/gi, ''); h = h.replace(/<param([^>]*)>/gi, function(a, b) {return '<span ' + b.replace(/value=/gi, '_mce_value=') + ' class="mceItemParam"></span>'}); h = h.replace(/\/ class=\"mceItemParam\"><\/span>/gi, 'class="mceItemParam"></span>'); o.content = h; }, _buildObj : function(o, n) { var ob, ed = this.editor, dom = ed.dom, p = this._parse(n.title), stc; stc = ed.getParam('media_strict', true) && o.type == 'application/x-shockwave-flash'; p.width = o.width = dom.getAttrib(n, 'width') || 100; p.height = o.height = dom.getAttrib(n, 'height') || 100; if (p.src) p.src = ed.convertURL(p.src, 'src', n); if (stc) { ob = dom.create('span', { id : p.id, _mce_name : 'object', type : 'application/x-shockwave-flash', data : p.src, style : dom.getAttrib(n, 'style'), width : o.width, height : o.height }); } else { ob = dom.create('span', { id : p.id, _mce_name : 'object', classid : "clsid:" + o.classid, style : dom.getAttrib(n, 'style'), codebase : o.codebase, width : o.width, height : o.height }); } each (p, function(v, k) { if (!/^(width|height|codebase|classid|id|_cx|_cy)$/.test(k)) { // Use url instead of src in IE for Windows media if (o.type == 'application/x-mplayer2' && k == 'src' && !p.url) k = 'url'; if (v) dom.add(ob, 'span', {_mce_name : 'param', name : k, '_mce_value' : v}); } }); if (!stc) dom.add(ob, 'span', tinymce.extend({_mce_name : 'embed', type : o.type, style : dom.getAttrib(n, 'style')}, p)); return ob; }, _spansToImgs : function(p) { var t = this, dom = t.editor.dom, im, ci; each(dom.select('span', p), function(n) { // Convert object into image if (dom.getAttrib(n, 'class') == 'mceItemObject') { ci = dom.getAttrib(n, "classid").toLowerCase().replace(/\s+/g, ''); switch (ci) { case 'clsid:d27cdb6e-ae6d-11cf-96b8-444553540000': dom.replace(t._createImg('mceItemFlash', n), n); break; case 'clsid:166b1bca-3f9c-11cf-8075-444553540000': dom.replace(t._createImg('mceItemShockWave', n), n); break; case 'clsid:6bf52a52-394a-11d3-b153-00c04f79faa6': case 'clsid:22d6f312-b0f6-11d0-94ab-0080c74c7e95': case 'clsid:05589fa1-c356-11ce-bf01-00aa0055595a': dom.replace(t._createImg('mceItemWindowsMedia', n), n); break; case 'clsid:02bf25d5-8c17-4b23-bc80-d3488abddc6b': dom.replace(t._createImg('mceItemQuickTime', n), n); break; case 'clsid:cfcdaa03-8be4-11cf-b84b-0020afbbccfa': dom.replace(t._createImg('mceItemRealMedia', n), n); break; default: dom.replace(t._createImg('mceItemFlash', n), n); } return; } // Convert embed into image if (dom.getAttrib(n, 'class') == 'mceItemEmbed') { switch (dom.getAttrib(n, 'type')) { case 'application/x-shockwave-flash': dom.replace(t._createImg('mceItemFlash', n), n); break; case 'application/x-director': dom.replace(t._createImg('mceItemShockWave', n), n); break; case 'application/x-mplayer2': dom.replace(t._createImg('mceItemWindowsMedia', n), n); break; case 'video/quicktime': dom.replace(t._createImg('mceItemQuickTime', n), n); break; case 'audio/x-pn-realaudio-plugin': dom.replace(t._createImg('mceItemRealMedia', n), n); break; default: dom.replace(t._createImg('mceItemFlash', n), n); } } }); }, _createImg : function(cl, n) { var im, dom = this.editor.dom, pa = {}, ti = '', args; args = ['id', 'name', 'width', 'height', 'bgcolor', 'align', 'flashvars', 'src', 'wmode', 'allowfullscreen', 'quality', 'data']; // Create image im = dom.create('img', { src : this.url + '/img/trans.gif', width : dom.getAttrib(n, 'width') || 100, height : dom.getAttrib(n, 'height') || 100, style : dom.getAttrib(n, 'style'), 'class' : cl }); // Setup base parameters each(args, function(na) { var v = dom.getAttrib(n, na); if (v) pa[na] = v; }); // Add optional parameters each(dom.select('span', n), function(n) { if (dom.hasClass(n, 'mceItemParam')) pa[dom.getAttrib(n, 'name')] = dom.getAttrib(n, '_mce_value'); }); // Use src not movie if (pa.movie) { pa.src = pa.movie; delete pa.movie; } // No src try data if (!pa.src) { pa.src = pa.data; delete pa.data; } // Merge with embed args n = dom.select('.mceItemEmbed', n)[0]; if (n) { each(args, function(na) { var v = dom.getAttrib(n, na); if (v && !pa[na]) pa[na] = v; }); } delete pa.width; delete pa.height; im.title = this._serialize(pa); return im; }, _parse : function(s) { return tinymce.util.JSON.parse('{' + s + '}'); }, _serialize : function(o) { return tinymce.util.JSON.serialize(o).replace(/[{}]/g, ''); } }); // Register plugin tinymce.PluginManager.add('media', tinymce.plugins.MediaPlugin); })();
JavaScript
/** * editor_plugin_src.js * * Copyright 2009, Moxiecode Systems AB * Released under LGPL License. * * License: http://tinymce.moxiecode.com/license * Contributing: http://tinymce.moxiecode.com/contributing */ (function() { tinymce.create('tinymce.plugins.BBCodePlugin', { init : function(ed, url) { var t = this, dialect = ed.getParam('bbcode_dialect', 'punbb').toLowerCase(); ed.onBeforeSetContent.add(function(ed, o) { o.content = t['_' + dialect + '_bbcode2html'](o.content); }); ed.onPostProcess.add(function(ed, o) { if (o.set) o.content = t['_' + dialect + '_bbcode2html'](o.content); if (o.get) o.content = t['_' + dialect + '_html2bbcode'](o.content); }); }, getInfo : function() { return { longname : 'BBCode Plugin', author : 'Moxiecode Systems AB', authorurl : 'http://tinymce.moxiecode.com', infourl : 'http://wiki.moxiecode.com/index.php/TinyMCE:Plugins/bbcode', version : tinymce.majorVersion + "." + tinymce.minorVersion }; }, // Private methods // HTML -> BBCode in PunBB dialect _punbb_html2bbcode : function(s) { s = tinymce.trim(s); function rep(re, str) { s = s.replace(re, str); }; // example: <strong> to [b] rep(/<a.*?href=\"(.*?)\".*?>(.*?)<\/a>/gi,"[url=$1]$2[/url]"); rep(/<font.*?color=\"(.*?)\".*?class=\"codeStyle\".*?>(.*?)<\/font>/gi,"[code][color=$1]$2[/color][/code]"); rep(/<font.*?color=\"(.*?)\".*?class=\"quoteStyle\".*?>(.*?)<\/font>/gi,"[quote][color=$1]$2[/color][/quote]"); rep(/<font.*?class=\"codeStyle\".*?color=\"(.*?)\".*?>(.*?)<\/font>/gi,"[code][color=$1]$2[/color][/code]"); rep(/<font.*?class=\"quoteStyle\".*?color=\"(.*?)\".*?>(.*?)<\/font>/gi,"[quote][color=$1]$2[/color][/quote]"); rep(/<span style=\"color: ?(.*?);\">(.*?)<\/span>/gi,"[color=$1]$2[/color]"); rep(/<font.*?color=\"(.*?)\".*?>(.*?)<\/font>/gi,"[color=$1]$2[/color]"); rep(/<span style=\"font-size:(.*?);\">(.*?)<\/span>/gi,"[size=$1]$2[/size]"); rep(/<font>(.*?)<\/font>/gi,"$1"); rep(/<img.*?src=\"(.*?)\".*?\/>/gi,"[img]$1[/img]"); rep(/<span class=\"codeStyle\">(.*?)<\/span>/gi,"[code]$1[/code]"); rep(/<span class=\"quoteStyle\">(.*?)<\/span>/gi,"[quote]$1[/quote]"); rep(/<strong class=\"codeStyle\">(.*?)<\/strong>/gi,"[code][b]$1[/b][/code]"); rep(/<strong class=\"quoteStyle\">(.*?)<\/strong>/gi,"[quote][b]$1[/b][/quote]"); rep(/<em class=\"codeStyle\">(.*?)<\/em>/gi,"[code][i]$1[/i][/code]"); rep(/<em class=\"quoteStyle\">(.*?)<\/em>/gi,"[quote][i]$1[/i][/quote]"); rep(/<u class=\"codeStyle\">(.*?)<\/u>/gi,"[code][u]$1[/u][/code]"); rep(/<u class=\"quoteStyle\">(.*?)<\/u>/gi,"[quote][u]$1[/u][/quote]"); rep(/<\/(strong|b)>/gi,"[/b]"); rep(/<(strong|b)>/gi,"[b]"); rep(/<\/(em|i)>/gi,"[/i]"); rep(/<(em|i)>/gi,"[i]"); rep(/<\/u>/gi,"[/u]"); rep(/<span style=\"text-decoration: ?underline;\">(.*?)<\/span>/gi,"[u]$1[/u]"); rep(/<u>/gi,"[u]"); rep(/<blockquote[^>]*>/gi,"[quote]"); rep(/<\/blockquote>/gi,"[/quote]"); rep(/<br \/>/gi,"\n"); rep(/<br\/>/gi,"\n"); rep(/<br>/gi,"\n"); rep(/<p>/gi,""); rep(/<\/p>/gi,"\n"); rep(/&nbsp;/gi," "); rep(/&quot;/gi,"\""); rep(/&lt;/gi,"<"); rep(/&gt;/gi,">"); rep(/&amp;/gi,"&"); return s; }, // BBCode -> HTML from PunBB dialect _punbb_bbcode2html : function(s) { s = tinymce.trim(s); function rep(re, str) { s = s.replace(re, str); }; // example: [b] to <strong> rep(/\n/gi,"<br />"); rep(/\[b\]/gi,"<strong>"); rep(/\[\/b\]/gi,"</strong>"); rep(/\[i\]/gi,"<em>"); rep(/\[\/i\]/gi,"</em>"); rep(/\[u\]/gi,"<u>"); rep(/\[\/u\]/gi,"</u>"); rep(/\[url=([^\]]+)\](.*?)\[\/url\]/gi,"<a href=\"$1\">$2</a>"); rep(/\[url\](.*?)\[\/url\]/gi,"<a href=\"$1\">$1</a>"); rep(/\[img\](.*?)\[\/img\]/gi,"<img src=\"$1\" />"); rep(/\[color=(.*?)\](.*?)\[\/color\]/gi,"<font color=\"$1\">$2</font>"); rep(/\[code\](.*?)\[\/code\]/gi,"<span class=\"codeStyle\">$1</span>&nbsp;"); rep(/\[quote.*?\](.*?)\[\/quote\]/gi,"<span class=\"quoteStyle\">$1</span>&nbsp;"); return s; } }); // Register plugin tinymce.PluginManager.add('bbcode', tinymce.plugins.BBCodePlugin); })();
JavaScript
/** * editor_plugin_src.js * * Copyright 2009, Moxiecode Systems AB * Released under LGPL License. * * License: http://tinymce.moxiecode.com/license * Contributing: http://tinymce.moxiecode.com/contributing */ (function() { var DOM = tinymce.DOM; tinymce.create('tinymce.plugins.FullScreenPlugin', { init : function(ed, url) { var t = this, s = {}, vp; t.editor = ed; // Register commands ed.addCommand('mceFullScreen', function() { var win, de = DOM.doc.documentElement; if (ed.getParam('fullscreen_is_enabled')) { if (ed.getParam('fullscreen_new_window')) closeFullscreen(); // Call to close in new window else { DOM.win.setTimeout(function() { tinymce.dom.Event.remove(DOM.win, 'resize', t.resizeFunc); tinyMCE.get(ed.getParam('fullscreen_editor_id')).setContent(ed.getContent({format : 'raw'}), {format : 'raw'}); tinyMCE.remove(ed); DOM.remove('mce_fullscreen_container'); de.style.overflow = ed.getParam('fullscreen_html_overflow'); DOM.setStyle(DOM.doc.body, 'overflow', ed.getParam('fullscreen_overflow')); DOM.win.scrollTo(ed.getParam('fullscreen_scrollx'), ed.getParam('fullscreen_scrolly')); tinyMCE.settings = tinyMCE.oldSettings; // Restore old settings }, 10); } return; } if (ed.getParam('fullscreen_new_window')) { win = DOM.win.open(url + "/fullscreen.htm", "mceFullScreenPopup", "fullscreen=yes,menubar=no,toolbar=no,scrollbars=no,resizable=yes,left=0,top=0,width=" + screen.availWidth + ",height=" + screen.availHeight); try { win.resizeTo(screen.availWidth, screen.availHeight); } catch (e) { // Ignore } } else { tinyMCE.oldSettings = tinyMCE.settings; // Store old settings s.fullscreen_overflow = DOM.getStyle(DOM.doc.body, 'overflow', 1) || 'auto'; s.fullscreen_html_overflow = DOM.getStyle(de, 'overflow', 1); vp = DOM.getViewPort(); s.fullscreen_scrollx = vp.x; s.fullscreen_scrolly = vp.y; // Fixes an Opera bug where the scrollbars doesn't reappear if (tinymce.isOpera && s.fullscreen_overflow == 'visible') s.fullscreen_overflow = 'auto'; // Fixes an IE bug where horizontal scrollbars would appear if (tinymce.isIE && s.fullscreen_overflow == 'scroll') s.fullscreen_overflow = 'auto'; // Fixes an IE bug where the scrollbars doesn't reappear if (tinymce.isIE && (s.fullscreen_html_overflow == 'visible' || s.fullscreen_html_overflow == 'scroll')) s.fullscreen_html_overflow = 'auto'; if (s.fullscreen_overflow == '0px') s.fullscreen_overflow = ''; DOM.setStyle(DOM.doc.body, 'overflow', 'hidden'); de.style.overflow = 'hidden'; //Fix for IE6/7 vp = DOM.getViewPort(); DOM.win.scrollTo(0, 0); if (tinymce.isIE) vp.h -= 1; n = DOM.add(DOM.doc.body, 'div', {id : 'mce_fullscreen_container', style : 'position:' + (tinymce.isIE6 || (tinymce.isIE && !DOM.boxModel) ? 'absolute' : 'fixed') + ';top:0;left:0;width:' + vp.w + 'px;height:' + vp.h + 'px;z-index:200000;'}); DOM.add(n, 'div', {id : 'mce_fullscreen'}); tinymce.each(ed.settings, function(v, n) { s[n] = v; }); s.id = 'mce_fullscreen'; s.width = n.clientWidth; s.height = n.clientHeight - 15; s.fullscreen_is_enabled = true; s.fullscreen_editor_id = ed.id; s.theme_advanced_resizing = false; s.save_onsavecallback = function() { ed.setContent(tinyMCE.get(s.id).getContent({format : 'raw'}), {format : 'raw'}); ed.execCommand('mceSave'); }; tinymce.each(ed.getParam('fullscreen_settings'), function(v, k) { s[k] = v; }); if (s.theme_advanced_toolbar_location === 'external') s.theme_advanced_toolbar_location = 'top'; t.fullscreenEditor = new tinymce.Editor('mce_fullscreen', s); t.fullscreenEditor.onInit.add(function() { t.fullscreenEditor.setContent(ed.getContent()); t.fullscreenEditor.focus(); }); t.fullscreenEditor.render(); t.fullscreenElement = new tinymce.dom.Element('mce_fullscreen_container'); t.fullscreenElement.update(); //document.body.overflow = 'hidden'; t.resizeFunc = tinymce.dom.Event.add(DOM.win, 'resize', function() { var vp = tinymce.DOM.getViewPort(), fed = t.fullscreenEditor, outerSize, innerSize; // Get outer/inner size to get a delta size that can be used to calc the new iframe size outerSize = fed.dom.getSize(fed.getContainer().firstChild); innerSize = fed.dom.getSize(fed.getContainer().getElementsByTagName('iframe')[0]); fed.theme.resizeTo(vp.w - outerSize.w + innerSize.w, vp.h - outerSize.h + innerSize.h); }); } }); // Register buttons ed.addButton('fullscreen', {title : 'fullscreen.desc', cmd : 'mceFullScreen'}); ed.onNodeChange.add(function(ed, cm) { cm.setActive('fullscreen', ed.getParam('fullscreen_is_enabled')); }); }, getInfo : function() { return { longname : 'Fullscreen', author : 'Moxiecode Systems AB', authorurl : 'http://tinymce.moxiecode.com', infourl : 'http://wiki.moxiecode.com/index.php/TinyMCE:Plugins/fullscreen', version : tinymce.majorVersion + "." + tinymce.minorVersion }; } }); // Register plugin tinymce.PluginManager.add('fullscreen', tinymce.plugins.FullScreenPlugin); })();
JavaScript
/** * editor_plugin_src.js * * Copyright 2009, Moxiecode Systems AB * Released under LGPL License. * * License: http://tinymce.moxiecode.com/license * Contributing: http://tinymce.moxiecode.com/contributing */ (function() { tinymce.create('tinymce.plugins.Save', { init : function(ed, url) { var t = this; t.editor = ed; // Register commands ed.addCommand('mceSave', t._save, t); ed.addCommand('mceCancel', t._cancel, t); // Register buttons ed.addButton('save', {title : 'save.save_desc', cmd : 'mceSave'}); ed.addButton('cancel', {title : 'save.cancel_desc', cmd : 'mceCancel'}); ed.onNodeChange.add(t._nodeChange, t); ed.addShortcut('ctrl+s', ed.getLang('save.save_desc'), 'mceSave'); }, getInfo : function() { return { longname : 'Save', author : 'Moxiecode Systems AB', authorurl : 'http://tinymce.moxiecode.com', infourl : 'http://wiki.moxiecode.com/index.php/TinyMCE:Plugins/save', version : tinymce.majorVersion + "." + tinymce.minorVersion }; }, // Private methods _nodeChange : function(ed, cm, n) { var ed = this.editor; if (ed.getParam('save_enablewhendirty')) { cm.setDisabled('save', !ed.isDirty()); cm.setDisabled('cancel', !ed.isDirty()); } }, // Private methods _save : function() { var ed = this.editor, formObj, os, i, elementId; formObj = tinymce.DOM.get(ed.id).form || tinymce.DOM.getParent(ed.id, 'form'); if (ed.getParam("save_enablewhendirty") && !ed.isDirty()) return; tinyMCE.triggerSave(); // Use callback instead if (os = ed.getParam("save_onsavecallback")) { if (ed.execCallback('save_onsavecallback', ed)) { ed.startContent = tinymce.trim(ed.getContent({format : 'raw'})); ed.nodeChanged(); } return; } if (formObj) { ed.isNotDirty = true; if (formObj.onsubmit == null || formObj.onsubmit() != false) formObj.submit(); ed.nodeChanged(); } else ed.windowManager.alert("Error: No form element found."); }, _cancel : function() { var ed = this.editor, os, h = tinymce.trim(ed.startContent); // Use callback instead if (os = ed.getParam("save_oncancelcallback")) { ed.execCallback('save_oncancelcallback', ed); return; } ed.setContent(h); ed.undoManager.clear(); ed.nodeChanged(); } }); // Register plugin tinymce.PluginManager.add('save', tinymce.plugins.Save); })();
JavaScript
/* Functions for the advlink plugin popup */ tinyMCEPopup.requireLangPack(); var templates = { "window.open" : "window.open('${url}','${target}','${options}')" }; function preinit() { var url; if (url = tinyMCEPopup.getParam("external_link_list_url")) document.write('<script language="javascript" type="text/javascript" src="' + tinyMCEPopup.editor.documentBaseURI.toAbsolute(url) + '"></script>'); } function changeClass() { var f = document.forms[0]; f.classes.value = getSelectValue(f, 'classlist'); } function init() { tinyMCEPopup.resizeToInnerSize(); var formObj = document.forms[0]; var inst = tinyMCEPopup.editor; var elm = inst.selection.getNode(); var action = "insert"; var html; document.getElementById('hrefbrowsercontainer').innerHTML = getBrowserHTML('hrefbrowser','href','file','advlink'); document.getElementById('popupurlbrowsercontainer').innerHTML = getBrowserHTML('popupurlbrowser','popupurl','file','advlink'); document.getElementById('linklisthrefcontainer').innerHTML = getLinkListHTML('linklisthref','href'); document.getElementById('anchorlistcontainer').innerHTML = getAnchorListHTML('anchorlist','href'); document.getElementById('targetlistcontainer').innerHTML = getTargetListHTML('targetlist','target'); // Link list html = getLinkListHTML('linklisthref','href'); if (html == "") document.getElementById("linklisthrefrow").style.display = 'none'; else document.getElementById("linklisthrefcontainer").innerHTML = html; // Resize some elements if (isVisible('hrefbrowser')) document.getElementById('href').style.width = '260px'; if (isVisible('popupurlbrowser')) document.getElementById('popupurl').style.width = '180px'; elm = inst.dom.getParent(elm, "A"); if (elm != null && elm.nodeName == "A") action = "update"; formObj.insert.value = tinyMCEPopup.getLang(action, 'Insert', true); setPopupControlsDisabled(true); if (action == "update") { var href = inst.dom.getAttrib(elm, 'href'); var onclick = inst.dom.getAttrib(elm, 'onclick'); // Setup form data setFormValue('href', href); setFormValue('title', inst.dom.getAttrib(elm, 'title')); setFormValue('id', inst.dom.getAttrib(elm, 'id')); setFormValue('style', inst.dom.getAttrib(elm, "style")); setFormValue('rel', inst.dom.getAttrib(elm, 'rel')); setFormValue('rev', inst.dom.getAttrib(elm, 'rev')); setFormValue('charset', inst.dom.getAttrib(elm, 'charset')); setFormValue('hreflang', inst.dom.getAttrib(elm, 'hreflang')); setFormValue('dir', inst.dom.getAttrib(elm, 'dir')); setFormValue('lang', inst.dom.getAttrib(elm, 'lang')); setFormValue('tabindex', inst.dom.getAttrib(elm, 'tabindex', typeof(elm.tabindex) != "undefined" ? elm.tabindex : "")); setFormValue('accesskey', inst.dom.getAttrib(elm, 'accesskey', typeof(elm.accesskey) != "undefined" ? elm.accesskey : "")); setFormValue('type', inst.dom.getAttrib(elm, 'type')); setFormValue('onfocus', inst.dom.getAttrib(elm, 'onfocus')); setFormValue('onblur', inst.dom.getAttrib(elm, 'onblur')); setFormValue('onclick', onclick); setFormValue('ondblclick', inst.dom.getAttrib(elm, 'ondblclick')); setFormValue('onmousedown', inst.dom.getAttrib(elm, 'onmousedown')); setFormValue('onmouseup', inst.dom.getAttrib(elm, 'onmouseup')); setFormValue('onmouseover', inst.dom.getAttrib(elm, 'onmouseover')); setFormValue('onmousemove', inst.dom.getAttrib(elm, 'onmousemove')); setFormValue('onmouseout', inst.dom.getAttrib(elm, 'onmouseout')); setFormValue('onkeypress', inst.dom.getAttrib(elm, 'onkeypress')); setFormValue('onkeydown', inst.dom.getAttrib(elm, 'onkeydown')); setFormValue('onkeyup', inst.dom.getAttrib(elm, 'onkeyup')); setFormValue('target', inst.dom.getAttrib(elm, 'target')); setFormValue('classes', inst.dom.getAttrib(elm, 'class')); // Parse onclick data if (onclick != null && onclick.indexOf('window.open') != -1) parseWindowOpen(onclick); else parseFunction(onclick); // Select by the values selectByValue(formObj, 'dir', inst.dom.getAttrib(elm, 'dir')); selectByValue(formObj, 'rel', inst.dom.getAttrib(elm, 'rel')); selectByValue(formObj, 'rev', inst.dom.getAttrib(elm, 'rev')); selectByValue(formObj, 'linklisthref', href); if (href.charAt(0) == '#') selectByValue(formObj, 'anchorlist', href); addClassesToList('classlist', 'advlink_styles'); selectByValue(formObj, 'classlist', inst.dom.getAttrib(elm, 'class'), true); selectByValue(formObj, 'targetlist', inst.dom.getAttrib(elm, 'target'), true); } else addClassesToList('classlist', 'advlink_styles'); } function checkPrefix(n) { if (n.value && Validator.isEmail(n) && !/^\s*mailto:/i.test(n.value) && confirm(tinyMCEPopup.getLang('advlink_dlg.is_email'))) n.value = 'mailto:' + n.value; if (/^\s*www\./i.test(n.value) && confirm(tinyMCEPopup.getLang('advlink_dlg.is_external'))) n.value = 'http://' + n.value; } function setFormValue(name, value) { document.forms[0].elements[name].value = value; } function parseWindowOpen(onclick) { var formObj = document.forms[0]; // Preprocess center code if (onclick.indexOf('return false;') != -1) { formObj.popupreturn.checked = true; onclick = onclick.replace('return false;', ''); } else formObj.popupreturn.checked = false; var onClickData = parseLink(onclick); if (onClickData != null) { formObj.ispopup.checked = true; setPopupControlsDisabled(false); var onClickWindowOptions = parseOptions(onClickData['options']); var url = onClickData['url']; formObj.popupname.value = onClickData['target']; formObj.popupurl.value = url; formObj.popupwidth.value = getOption(onClickWindowOptions, 'width'); formObj.popupheight.value = getOption(onClickWindowOptions, 'height'); formObj.popupleft.value = getOption(onClickWindowOptions, 'left'); formObj.popuptop.value = getOption(onClickWindowOptions, 'top'); if (formObj.popupleft.value.indexOf('screen') != -1) formObj.popupleft.value = "c"; if (formObj.popuptop.value.indexOf('screen') != -1) formObj.popuptop.value = "c"; formObj.popuplocation.checked = getOption(onClickWindowOptions, 'location') == "yes"; formObj.popupscrollbars.checked = getOption(onClickWindowOptions, 'scrollbars') == "yes"; formObj.popupmenubar.checked = getOption(onClickWindowOptions, 'menubar') == "yes"; formObj.popupresizable.checked = getOption(onClickWindowOptions, 'resizable') == "yes"; formObj.popuptoolbar.checked = getOption(onClickWindowOptions, 'toolbar') == "yes"; formObj.popupstatus.checked = getOption(onClickWindowOptions, 'status') == "yes"; formObj.popupdependent.checked = getOption(onClickWindowOptions, 'dependent') == "yes"; buildOnClick(); } } function parseFunction(onclick) { var formObj = document.forms[0]; var onClickData = parseLink(onclick); // TODO: Add stuff here } function getOption(opts, name) { return typeof(opts[name]) == "undefined" ? "" : opts[name]; } function setPopupControlsDisabled(state) { var formObj = document.forms[0]; formObj.popupname.disabled = state; formObj.popupurl.disabled = state; formObj.popupwidth.disabled = state; formObj.popupheight.disabled = state; formObj.popupleft.disabled = state; formObj.popuptop.disabled = state; formObj.popuplocation.disabled = state; formObj.popupscrollbars.disabled = state; formObj.popupmenubar.disabled = state; formObj.popupresizable.disabled = state; formObj.popuptoolbar.disabled = state; formObj.popupstatus.disabled = state; formObj.popupreturn.disabled = state; formObj.popupdependent.disabled = state; setBrowserDisabled('popupurlbrowser', state); } function parseLink(link) { link = link.replace(new RegExp('&#39;', 'g'), "'"); var fnName = link.replace(new RegExp("\\s*([A-Za-z0-9\.]*)\\s*\\(.*", "gi"), "$1"); // Is function name a template function var template = templates[fnName]; if (template) { // Build regexp var variableNames = template.match(new RegExp("'?\\$\\{[A-Za-z0-9\.]*\\}'?", "gi")); var regExp = "\\s*[A-Za-z0-9\.]*\\s*\\("; var replaceStr = ""; for (var i=0; i<variableNames.length; i++) { // Is string value if (variableNames[i].indexOf("'${") != -1) regExp += "'(.*)'"; else // Number value regExp += "([0-9]*)"; replaceStr += "$" + (i+1); // Cleanup variable name variableNames[i] = variableNames[i].replace(new RegExp("[^A-Za-z0-9]", "gi"), ""); if (i != variableNames.length-1) { regExp += "\\s*,\\s*"; replaceStr += "<delim>"; } else regExp += ".*"; } regExp += "\\);?"; // Build variable array var variables = []; variables["_function"] = fnName; var variableValues = link.replace(new RegExp(regExp, "gi"), replaceStr).split('<delim>'); for (var i=0; i<variableNames.length; i++) variables[variableNames[i]] = variableValues[i]; return variables; } return null; } function parseOptions(opts) { if (opts == null || opts == "") return []; // Cleanup the options opts = opts.toLowerCase(); opts = opts.replace(/;/g, ","); opts = opts.replace(/[^0-9a-z=,]/g, ""); var optionChunks = opts.split(','); var options = []; for (var i=0; i<optionChunks.length; i++) { var parts = optionChunks[i].split('='); if (parts.length == 2) options[parts[0]] = parts[1]; } return options; } function buildOnClick() { var formObj = document.forms[0]; if (!formObj.ispopup.checked) { formObj.onclick.value = ""; return; } var onclick = "window.open('"; var url = formObj.popupurl.value; onclick += url + "','"; onclick += formObj.popupname.value + "','"; if (formObj.popuplocation.checked) onclick += "location=yes,"; if (formObj.popupscrollbars.checked) onclick += "scrollbars=yes,"; if (formObj.popupmenubar.checked) onclick += "menubar=yes,"; if (formObj.popupresizable.checked) onclick += "resizable=yes,"; if (formObj.popuptoolbar.checked) onclick += "toolbar=yes,"; if (formObj.popupstatus.checked) onclick += "status=yes,"; if (formObj.popupdependent.checked) onclick += "dependent=yes,"; if (formObj.popupwidth.value != "") onclick += "width=" + formObj.popupwidth.value + ","; if (formObj.popupheight.value != "") onclick += "height=" + formObj.popupheight.value + ","; if (formObj.popupleft.value != "") { if (formObj.popupleft.value != "c") onclick += "left=" + formObj.popupleft.value + ","; else onclick += "left='+(screen.availWidth/2-" + (formObj.popupwidth.value/2) + ")+',"; } if (formObj.popuptop.value != "") { if (formObj.popuptop.value != "c") onclick += "top=" + formObj.popuptop.value + ","; else onclick += "top='+(screen.availHeight/2-" + (formObj.popupheight.value/2) + ")+',"; } if (onclick.charAt(onclick.length-1) == ',') onclick = onclick.substring(0, onclick.length-1); onclick += "');"; if (formObj.popupreturn.checked) onclick += "return false;"; // tinyMCE.debug(onclick); formObj.onclick.value = onclick; if (formObj.href.value == "") formObj.href.value = url; } function setAttrib(elm, attrib, value) { var formObj = document.forms[0]; var valueElm = formObj.elements[attrib.toLowerCase()]; var dom = tinyMCEPopup.editor.dom; if (typeof(value) == "undefined" || value == null) { value = ""; if (valueElm) value = valueElm.value; } // Clean up the style if (attrib == 'style') value = dom.serializeStyle(dom.parseStyle(value), 'a'); dom.setAttrib(elm, attrib, value); } function getAnchorListHTML(id, target) { var inst = tinyMCEPopup.editor; var nodes = inst.dom.select('a.mceItemAnchor,img.mceItemAnchor'), name, i; var html = ""; html += '<select id="' + id + '" name="' + id + '" class="mceAnchorList" o2nfocus="tinyMCE.addSelectAccessibility(event, this, window);" onchange="this.form.' + target + '.value='; html += 'this.options[this.selectedIndex].value;">'; html += '<option value="">---</option>'; for (i=0; i<nodes.length; i++) { if ((name = inst.dom.getAttrib(nodes[i], "name")) != "") html += '<option value="#' + name + '">' + name + '</option>'; } html += '</select>'; return html; } function insertAction() { var inst = tinyMCEPopup.editor; var elm, elementArray, i; elm = inst.selection.getNode(); checkPrefix(document.forms[0].href); elm = inst.dom.getParent(elm, "A"); // Remove element if there is no href if (!document.forms[0].href.value) { tinyMCEPopup.execCommand("mceBeginUndoLevel"); i = inst.selection.getBookmark(); inst.dom.remove(elm, 1); inst.selection.moveToBookmark(i); tinyMCEPopup.execCommand("mceEndUndoLevel"); tinyMCEPopup.close(); return; } tinyMCEPopup.execCommand("mceBeginUndoLevel"); // Create new anchor elements if (elm == null) { inst.getDoc().execCommand("unlink", false, null); tinyMCEPopup.execCommand("CreateLink", false, "#mce_temp_url#", {skip_undo : 1}); elementArray = tinymce.grep(inst.dom.select("a"), function(n) {return inst.dom.getAttrib(n, 'href') == '#mce_temp_url#';}); for (i=0; i<elementArray.length; i++) setAllAttribs(elm = elementArray[i]); } else setAllAttribs(elm); // Don't move caret if selection was image if (elm.childNodes.length != 1 || elm.firstChild.nodeName != 'IMG') { inst.focus(); inst.selection.select(elm); inst.selection.collapse(0); tinyMCEPopup.storeSelection(); } tinyMCEPopup.execCommand("mceEndUndoLevel"); tinyMCEPopup.close(); } function setAllAttribs(elm) { var formObj = document.forms[0]; var href = formObj.href.value; var target = getSelectValue(formObj, 'targetlist'); setAttrib(elm, 'href', href); setAttrib(elm, 'title'); setAttrib(elm, 'target', target == '_self' ? '' : target); setAttrib(elm, 'id'); setAttrib(elm, 'style'); setAttrib(elm, 'class', getSelectValue(formObj, 'classlist')); setAttrib(elm, 'rel'); setAttrib(elm, 'rev'); setAttrib(elm, 'charset'); setAttrib(elm, 'hreflang'); setAttrib(elm, 'dir'); setAttrib(elm, 'lang'); setAttrib(elm, 'tabindex'); setAttrib(elm, 'accesskey'); setAttrib(elm, 'type'); setAttrib(elm, 'onfocus'); setAttrib(elm, 'onblur'); setAttrib(elm, 'onclick'); setAttrib(elm, 'ondblclick'); setAttrib(elm, 'onmousedown'); setAttrib(elm, 'onmouseup'); setAttrib(elm, 'onmouseover'); setAttrib(elm, 'onmousemove'); setAttrib(elm, 'onmouseout'); setAttrib(elm, 'onkeypress'); setAttrib(elm, 'onkeydown'); setAttrib(elm, 'onkeyup'); // Refresh in old MSIE if (tinyMCE.isMSIE5) elm.outerHTML = elm.outerHTML; } function getSelectValue(form_obj, field_name) { var elm = form_obj.elements[field_name]; if (!elm || elm.options == null || elm.selectedIndex == -1) return ""; return elm.options[elm.selectedIndex].value; } function getLinkListHTML(elm_id, target_form_element, onchange_func) { if (typeof(tinyMCELinkList) == "undefined" || tinyMCELinkList.length == 0) return ""; var html = ""; html += '<select id="' + elm_id + '" name="' + elm_id + '"'; html += ' class="mceLinkList" onfoc2us="tinyMCE.addSelectAccessibility(event, this, window);" onchange="this.form.' + target_form_element + '.value='; html += 'this.options[this.selectedIndex].value;'; if (typeof(onchange_func) != "undefined") html += onchange_func + '(\'' + target_form_element + '\',this.options[this.selectedIndex].text,this.options[this.selectedIndex].value);'; html += '"><option value="">---</option>'; for (var i=0; i<tinyMCELinkList.length; i++) html += '<option value="' + tinyMCELinkList[i][1] + '">' + tinyMCELinkList[i][0] + '</option>'; html += '</select>'; return html; // tinyMCE.debug('-- image list start --', html, '-- image list end --'); } function getTargetListHTML(elm_id, target_form_element) { var targets = tinyMCEPopup.getParam('theme_advanced_link_targets', '').split(';'); var html = ''; html += '<select id="' + elm_id + '" name="' + elm_id + '" onf2ocus="tinyMCE.addSelectAccessibility(event, this, window);" onchange="this.form.' + target_form_element + '.value='; html += 'this.options[this.selectedIndex].value;">'; html += '<option value="_self">' + tinyMCEPopup.getLang('advlink_dlg.target_same') + '</option>'; html += '<option value="_blank">' + tinyMCEPopup.getLang('advlink_dlg.target_blank') + ' (_blank)</option>'; html += '<option value="_parent">' + tinyMCEPopup.getLang('advlink_dlg.target_parent') + ' (_parent)</option>'; html += '<option value="_top">' + tinyMCEPopup.getLang('advlink_dlg.target_top') + ' (_top)</option>'; for (var i=0; i<targets.length; i++) { var key, value; if (targets[i] == "") continue; key = targets[i].split('=')[0]; value = targets[i].split('=')[1]; html += '<option value="' + key + '">' + value + ' (' + key + ')</option>'; } html += '</select>'; return html; } // While loading preinit(); tinyMCEPopup.onInit.add(init);
JavaScript
tinyMCE.addI18n('en.advlink_dlg',{ title:"Insert/edit link", url:"Link URL", target:"Target", titlefield:"Title", is_email:"The URL you entered seems to be an email address, do you want to add the required mailto: prefix?", is_external:"The URL you entered seems to external link, do you want to add the required http:// prefix?", list:"Link list", general_tab:"General", popup_tab:"Popup", events_tab:"Events", advanced_tab:"Advanced", general_props:"General properties", popup_props:"Popup properties", event_props:"Events", advanced_props:"Advanced properties", popup_opts:"Options", anchor_names:"Anchors", target_same:"Open in this window / frame", target_parent:"Open in parent window / frame", target_top:"Open in top frame (replaces all frames)", target_blank:"Open in new window", popup:"Javascript popup", popup_url:"Popup URL", popup_name:"Window name", popup_return:"Insert 'return false'", popup_scrollbars:"Show scrollbars", popup_statusbar:"Show status bar", popup_toolbar:"Show toolbars", popup_menubar:"Show menu bar", popup_location:"Show location bar", popup_resizable:"Make window resizable", popup_dependent:"Dependent (Mozilla/Firefox only)", popup_size:"Size", popup_position:"Position (X/Y)", id:"Id", style:"Style", classes:"Classes", target_name:"Target name", langdir:"Language direction", target_langcode:"Target language", langcode:"Language code", encoding:"Target character encoding", mime:"Target MIME type", rel:"Relationship page to target", rev:"Relationship target to page", tabindex:"Tabindex", accesskey:"Accesskey", ltr:"Left to right", rtl:"Right to left", link_list:"Link list" });
JavaScript
/** * editor_plugin_src.js * * Copyright 2009, Moxiecode Systems AB * Released under LGPL License. * * License: http://tinymce.moxiecode.com/license * Contributing: http://tinymce.moxiecode.com/contributing */ (function() { tinymce.create('tinymce.plugins.AdvancedLinkPlugin', { init : function(ed, url) { this.editor = ed; // Register commands ed.addCommand('mceAdvLink', function() { var se = ed.selection; // No selection and not in link if (se.isCollapsed() && !ed.dom.getParent(se.getNode(), 'A')) return; ed.windowManager.open({ file : url + '/link.htm', width : 480 + parseInt(ed.getLang('advlink.delta_width', 0)), height : 400 + parseInt(ed.getLang('advlink.delta_height', 0)), inline : 1 }, { plugin_url : url }); }); // Register buttons ed.addButton('link', { title : 'advlink.link_desc', cmd : 'mceAdvLink' }); ed.addShortcut('ctrl+k', 'advlink.advlink_desc', 'mceAdvLink'); ed.onNodeChange.add(function(ed, cm, n, co) { cm.setDisabled('link', co && n.nodeName != 'A'); cm.setActive('link', n.nodeName == 'A' && !n.name); }); }, getInfo : function() { return { longname : 'Advanced link', author : 'Moxiecode Systems AB', authorurl : 'http://tinymce.moxiecode.com', infourl : 'http://wiki.moxiecode.com/index.php/TinyMCE:Plugins/advlink', version : tinymce.majorVersion + "." + tinymce.minorVersion }; } }); // Register plugin tinymce.PluginManager.add('advlink', tinymce.plugins.AdvancedLinkPlugin); })();
JavaScript
(function($){ window.EditDialog = { currentWin : $.WindowManager.find(window), init : function() { var t = this, args; args = t.args = $.extend({ path : '{0}', visual_path : '/' }, t.currentWin.getArgs()); if (t.currentWin.features) { t.currentWin.features.onbeforeclose = function() { // Temp file exists, ask to save if (t.imgPath != t.targetPath) { $.WindowManager.confirm($.translate('{#edit_image.confirm_no_save}'), function(s) { if (s) t.currentWin.close(); }); return false; // Block close } }; } $(window).bind('resize', function(e) { t.resizeView(); }); t.imageSelection = $.createImageSelection($('#editImage'), { scroll_container : $('#imageWrapper'), delta_x : 26 + ($.browser.msie ? 2 : 0), delta_y : 90 + ($.browser.msie ? 2 : 0) }); $(t.imageSelection).bind('imgselection:change', function(e, x, y, w, h) { var f = document.forms[0]; if (this.mode == 'resize') { f.resize_w.value = w; f.resize_h.value = h; } else { f.crop_x.value = x; f.crop_y.value = y; f.crop_w.value = w; f.crop_h.value = h; } }); t.loadImage({path : args.path, url : args.url, initial : 1}); t.resizeView(); $(['save', 'revert', 'crop', 'resize', 'flip', 'rotate']).each(function(i, v) { var a = $('#' + v); a.click(function() { if (!a.hasClass('disabled') && !a.hasClass('active')) { t[v](); $('div.panel').hide(); $('#' + v + '_tools').show(); a.addClass('active'); } }); }); $('a.apply').click(function(e) {t.apply();}); $('a.cancel').click(function(e) {t.cancel();}); }, apply : function() { }, cancel : function() { $('div.panel').hide(); $('#toolbar a').removeClass('active'); this.imageSelection.setMode('none'); if (this.imgUtils) { this.imgUtils.destroy(); this.imgUtils = null; } $.WindowManager.hideProgress(); }, save : function() { var t = this, f = document.forms[0]; f.save_filename.value = t.targetPath.substring(t.targetPath.lastIndexOf('/') + 1); t.apply = function() { // Get replace mode RPC.exec('im.getConfig', {path : t.imgPath}, function(data) { var config = data.result, f = document.forms[0]; if (!RPC.handleError({message : 'Get config error', visual_path : t.args.visual_path, response : data})) { if (config['filesystem.clean_names'] == "true") $('#save_filename').val($.cleanName($('#save_filename').val())); $.WindowManager.showProgress({message : $.translate("{#edit_image.saving_wait}")}); RPC.exec('im.saveImage', {path : t.imgPath, target : $('#save_filename').val()}, function(data) { var res; $.WindowManager.hideProgress(); if (!RPC.handleError({message : 'Save error', visual_path : t.args.visual_path, response : data})) { res = RPC.toArray(data.result); if (t.args.onsave) return t.insertFile(res[0].file); if (res.length > 0) t.loadImage({path : res[0].file, initial : 1}); $('#save,#revert').addClass('disabled'); t.cancel(); } }); } }); }; }, revert : function(e) { var t = this; $.WindowManager.confirm($.translate("{#edit_image.confirm_revert}"), function(s) { if (s) { $('#save,#revert').addClass('disabled'); t.loadImage({path : t.targetPath}); } }); }, resize : function() { var t = this, f = document.forms[0]; t.cancel(); t.imageSelection.setMode('resize'); t.imageSelection.proportional = f.resize_prop.checked; $(f.resize_prop).click(function() { t.imageSelection.proportional = f.resize_prop.checked; }); $('#resize_tools input[@type=text]').change(function(e) { if (f.resize_prop.checked) { if (e.target.id == "resize_w") f.resize_h.value = Math.round(t.imageSelection.h * (parseInt(f.resize_w.value) / t.imageSelection.w)); else f.resize_w.value = Math.round(t.imageSelection.w * (parseInt(f.resize_h.value) / t.imageSelection.h)); } t.imageSelection.setRect(0, 0, parseInt(f.resize_w.value), parseInt(f.resize_h.value)); }); t.apply = function() { $.WindowManager.showProgress({message : $.translate('{#edit_image.please_wait}')}); t.execRPC('im.resizeImage', {path : t.imgPath, width : f.resize_w.value, height : f.resize_h.value, temp : true}, '{#error.resize_failed}'); }; }, crop : function() { var t = this, f = document.forms[0]; t.cancel(); t.imageSelection.setMode('crop'); t.imageSelection.proportional = f.crop_prop.checked; $(f.crop_prop).click(function() { t.imageSelection.proportional = f.crop_prop.checked; }); $('#crop_tools input[@type=text]').change(function(e) { if (f.crop_prop.checked) { if (e.target.id == "crop_w") f.crop_h.value = Math.round(t.imageSelection.h * (parseInt(f.crop_w.value) / t.imageSelection.w)); else f.crop_w.value = Math.round(t.imageSelection.w * (parseInt(f.crop_h.value) / t.imageSelection.h)); } t.imageSelection.setRect(parseInt(f.crop_x.value), parseInt(f.crop_y.value), parseInt(f.crop_w.value), parseInt(f.crop_h.value)); }); t.apply = function() { $.WindowManager.showProgress({message : $.translate('{#edit_image.please_wait}')}); t.execRPC('im.cropImage', {path : t.imgPath, left : f.crop_x.value, top : f.crop_y.value, width : f.crop_w.value, height : f.crop_h.value, temp : true}, '{#error.crop_failed}'); }; }, flip : function() { var t = this, f = document.forms[0], axis; $('#flip_tools input').attr('checked', ''); t.cancel(); t.imageSelection.setMode('none'); t.imgUtils = new $.ImageUtils($('#editImage')); $(t.imgUtils).bind('ImageUtils:load', function() { $('#flip_tools input').click(function() { t.imgUtils.flip(axis = $('#flip_tools input:checked').val()); }); t.apply = function() { $.WindowManager.showProgress({message : $.translate('{#edit_image.please_wait}')}); if (axis) t.execRPC('im.flipImage', {path : t.imgPath, horizontal : axis == 'h', vertical : axis == 'v', temp : true}, '{#error.flip_failed}'); else t.cancel(); }; }); t.imgUtils.render(); }, rotate : function() { var t = this, f = document.forms[0], ang; $('#rotate_tools input').attr('checked', ''); t.cancel(); t.imageSelection.setMode('none'); t.imgUtils = new $.ImageUtils($('#editImage')); $(t.imgUtils).bind('ImageUtils:load', function() { $('#rotate_tools input').click(function() { t.imgUtils.rotate(ang = parseInt($('#rotate_tools input:checked').val())); }); t.apply = function() { $.WindowManager.showProgress({message : $.translate('{#edit_image.please_wait}')}); if (ang) t.execRPC('im.rotateImage', {path : t.imgPath, angle : ang, temp : true}, '{#error.rotate_failed}'); else t.cancel(); }; }); t.imgUtils.render(); }, execRPC : function(m, a, er) { var t = this; RPC.exec(m, a, function(data) { var res = RPC.toArray(data.result); $.WindowManager.hideProgress(); if (!RPC.handleError({message : er, response : data})) { $('#save,#revert').removeClass('disabled'); t.loadImage({path : res[0].file}); } }); }, insertFile : function(p) { var t = this, s = t.args; RPC.insertFile({ relative_urls : s.relative_urls, document_base_url : s.document_base_url, default_base_url : s.default_base_url, no_host : s.remove_script_host || s.no_host, path : p, progress_message : $.translate("{#common.image_data}"), insert_filter : s.insert_filter, oninsert : function(o) { s.onsave(o); t.currentWin.close(); } }); }, loadImage : function(o, cb) { var t = this; $('#crop,#resize,#flip,#rotate').addClass('disabled'); $.WindowManager.showProgress({message : $.translate(o.initial ? "{#edit_image.loading}" : "{#edit_image.please_wait}")}); RPC.exec('im.getMediaInfo', {path : o.path, url : o.url}, function (data) { var res = RPC.toArray(data.result); if (!RPC.handleError({message : 'Generic error', response : data})) { if (o.initial) t.imageURL = res[0].url; // Initial load if (o.initial) t.targetPath = res[0].path; t.imgPath = res[0].path; $('#editImage').load(function() { $.WindowManager.hideProgress(); t.imageSelection.setImage($('#editImage')); $('#crop,#resize,#flip,#rotate').removeClass('disabled'); t.cancel(); }); $('#editImage').error(function() { $.WindowManager.hideProgress(); }); $('#editImage').attr('src', '../../stream/index.php?cmd=im.streamFile&path=' + escape(res[0].path) + '&rnd=' + new Date().getTime()); if (cb) cb(res); } }); }, resizeView : function() { $('#imageWrapper').css({'width' : (window.innerWidth || $.winWidth()) - 30, 'height' : (window.innerHeight || $.winHeight()) - 100}); }, isDemo : function() { if (this.args.is_demo) { $.WindowManager.info($.translate('{#error.demo}')); return true; } } }; $(function(e) { EditDialog.init(); }); })(jQuery);
JavaScript
(function($) { window.ImageManager = $.extend(BaseManager, { page : 0, pages : 0, pageSize : 25, viewMode : 'thumbs', tools : [ 'createdir', 'preview', 'refresh', 'edit', 'upload', 'rename', 'delete', 'download', 'insert', 'filemanager', 'help' ], init : function() { var t = this, args = t.currentWin.getArgs(), uri; // Compile templates t.type = 'im'; t.caregoryListTpl = $.templateFromScript('#folders_template'); t.foldersTpl = $.templateFromScript('#folders_template'); t.thumbTpl = $.templateFromScript('#thumb_template'); t.textTpl = $.templateFromScript('#text_template'); t.customDirsTpl = $.templateFromScript('#custom_dir_template'); t.path = args.path || '{default}'; t.rootPath = args.rootpath; t.extensions = args.extensions; t.include_file_pattern = args.include_file_pattern; t.exclude_file_pattern = args.exclude_file_pattern; t.include_directory_pattern = args.include_directory_pattern; t.exclude_directory_pattern = args.exclude_directory_pattern; t.remember_last_path = args.remember_last_path; t.urlSuffix = ''; if (document.domain != document.location.hostname) t.urlSuffix = '?domain=' + document.domain; if (args.url) { uri = $.parseURI(args.url, {base_url : args.document_base_url || args.default_base_url}); if (uri) t.inputURL = uri.path.replace(/\/[^\/]+$/, ''); } if (t.rootPath) { chunks = t.rootPath.split(/=/); t.rootPathName = chunks.length > 1 ? chunks[0] : /[^\/]+$/.exec(t.rootPath); t.rootPath = chunks[1] || t.rootPath; } // Add template helpers $.extend($.template.helpers, { add : function(v, a) { if (v != 'auto') v = parseInt(v) + parseInt(a) + 'px'; return v; } }); t.menu = new $.mcDropMenu({ halign : 'right', valign : 'bottom', setup : function(m) { $(m).bind('DropMenu:beforeshow', function(e, m) { var file = t.focusedFile; // Build new menu m.clear(); if (file.type != 'folder') m.add({title : $.translate('{#common.insert}'), disabled : t.isDisabled('insert'), onclick : function() {t.insertFiles();}}); m.add({title : $.translate('{#common.deleteit}'), disabled : t.isDisabled('delete'), onclick : function() {t.deleteFiles([file]);}}); if (file.type != 'folder') { if (file.custom.editable) m.add({title : $.translate('{#common.edit}'), disabled : t.isDisabled('edit'), onclick : function() {t.editFile(file);}}); m.add({title : $.translate('{#common.view}'), disabled : t.isDisabled('view'), onclick : function() {t.viewFile(file);}}); } }); } }); $().bind('DropMenu:show', function(e, m) { $('#' + m.id).css('opacity', 0).animate({ opacity: 0.9 }, 300); }); t.menu.render('#filelist'); // Register toolbar actions $().bind('action:createdir', function() {t.createDir();}); $().bind('action:upload', function() {t.uploadFiles();}); $().bind('action:refresh', function() {t.listFiles();t.listDirs();}); $().bind('action:help', function() {}); $().bind('action:filemanager', function() {t.fileManager()}); $('#tools li').each(function(i, v) { $(v).click(function(e) { if (!$(v).hasClass('disabled')) $().trigger('action:' + v.id, e); e.preventDefault(); return false; }); }); $('#filelist').click(function(e) { var a = $(e.target).parents('a')[0], fo, o, div, img; if (a && a.rel) { div = $(a).parents('div.file')[0]; fo = t.focusedFile = t.files[div.id.replace(/[^0-9]/g, '')]; t.selectedFiles = [fo]; if (a.rel == 'file') { if (fo.type == 'folder' || fo.type == 'parent') { t.page = 0; t.listFiles(fo.path); t.listDirs(); } else t.insertFiles(); } else if (a.rel == 'menu') { img = $(a).find('img'); o = img.offset(); t.menu.show(o.left + img.width(), o.top); } e.preventDefault(); return false; } }); $('#folder_list, #special_list, #category_list').click(function(e) { var a = e.target.nodeName == 'A' ? e.target : $(e.target).parents('a')[0]; if (a) { t.page = 0; t.listFiles(a.title); t.listDirs(); } }); $('#selectView').change(function(e) { t.viewMode = $(e.target).val(); t.updateFileList(); }); $('#setPages').change(function(e) { t.page = 0; t.pageSize = $(e.target).val(); t.listFiles(); }); $('#curpage').change(function(e) { t.page = parseInt(e.target.value) - 1; t.listFiles(); }); $('#pages').click(function(e) { var el = e.target; if (el.nodeName == 'A') { if ($(el).hasClass('disabled')) return; if ($(el).hasClass('next')) t.page++; else if ($(el).hasClass('prev')) t.page--; t.listFiles(); e.preventDefault(); return false; } }); function filter(e) { var f = $(e.target).val(); if (f == t.filterVal) return; t.filterVal = f; if (f == '') f = null; else if (f.indexOf('*') == -1) f = '*' + f + '*'; t.page = 0; t.filter = f; t.listFiles(); t.listDirs(); }; $('#filter').change(filter).keyup(function(e) { if (e.keyCode == 13) filter(e); }); if (t.specialFolders.length) { $(t.specialFolders).each(function(i, v) { v.title = $.translate(v.title); $('#special_list').append(t.customDirsTpl, v); }); $('#special_list').show(); } setInterval(function() { RPC.exec('im.keepAlive', {}); }, 60 * 1000 * 5); // 5 min }, listFiles : function(p) { var t = this, args = t.currentWin.getArgs(); t.path = p || t.path; $('#pages').hide(); $('#progress').show(); $('#filelist').html(''); t.page = isNaN(t.page) || t.page < 0 ? 0 : t.page; if (t.pages) t.page = t.page > t.pages - 1 ? t.pages - 1 : t.page; RPC.exec('im.listFiles', { path : t.path, root_path : t.rootPath, url : t.inputURL, config : 'general,thumbnail,filesystem,filemanager', extensions : t.extensions, include_file_pattern : t.include_file_pattern, exclude_file_pattern : t.exclude_file_pattern, include_directory_pattern : t.include_directory_pattern, exclude_directory_pattern : t.exclude_directory_pattern, remember_last_path : !!t.remember_last_path, page : t.page, page_size : t.pageSize, filter : t.filter }, function(data) { var header, cfg, disabled, visible, argTools, argDisabledTools; if (!RPC.handleError({message : 'List files error', visual_path : t.visualPath, response : data})) { header = data.result.header; cfg = data.result.config; t.access = header.attribs; t.visualPath = header.visual_path; t.pages = parseInt(header.pages); t.config = cfg; t.fileManagerURL = cfg['filemanager.urlprefix']; t.demoMode = cfg['general.demo'] == "true"; t.path = header.path; function explode(s) { return s ? s.replace(/\s+/g, '').split(',') : s; }; // Enable/disable tools disabled = t.disabledTools = explode(cfg['general.disabled_tools']); visible = explode(cfg['general.tools']); if (argDisabledTools = explode(args.disabled_tools)) disabled = jQuery.merge(argDisabledTools, disabled); if (argTools = explode(args.tools)) { $(argTools).each(function(i, v) { if (!$.inArray(v, visible)) visible.push(v); }); visible = $.grep(visible, function(v) { return $.inArray(v, argTools); }); } $(t.tools).each(function(i, v) { var li = $('#' + v); t.setDisabled(v, $.inArray(v, disabled) != -1); if ($.inArray(v, visible) != -1) li.show(); else li.hide(); }); $('#tools').show(); $('#progress').hide(); $('#curpath').html(t.visualPath).attr('title', t.visualPath); // Convert result table into object list t.files = RPC.toArray(data.result); // Update file list t.updateFileList(); $().trigger('filelist:changed'); } }); }, updateFileList : function() { var t = this; fileLst = $('#filelist'); fileLst.html(''); $('#numpages').html(t.pages); $('#curpage').val(t.page + 1); $('#pages').show(); if (!t.page) $('#pages .prev').addClass('disabled'); else $('#pages .prev').removeClass('disabled'); if (t.page == t.pages - 1) $('#pages .next').addClass('disabled'); else $('#pages .next').removeClass('disabled'); $(t.files).each(function(i) { var r = this, cfg = t.config; r = $.extend({ index : i, thumburl : '../../stream/index.php?cmd=im.thumb&path=' + escape(r.path) + '&u=' + r.size, thumb_width : (parseInt(cfg["thumbnail.width"]) + 10) + 'px', thumb_height : (parseInt(cfg["thumbnail.height"]) + 10) + 'px', text_width : (parseInt(cfg["thumbnail.width"]) - 16) + 'px' }, this); if (r.custom.twidth) { r.width = r.custom.twidth + 'px'; r.height = r.custom.theight + 'px'; } else { r.width = r.height = 'auto'; r.thumburl = 'img/img_generic.png'; } switch (r.type) { case 'parent': r.thumburl = 'img/parent_big.gif'; break; case 'folder': r.thumburl = 'img/folder_big.gif'; break; case 'swf': case 'flv': r.thumburl = 'img/flash.gif'; break; case 'dcr': r.thumburl = 'img/dcr.gif'; break; case 'mov': case 'qt': r.thumburl = 'img/qt.gif'; break; case 'ram': case 'rm': r.thumburl = 'img/rm.gif'; break; case 'wmv': case 'avi': case 'mpg': case 'mpeg': case 'asf': r.thumburl = 'img/avi.gif'; break; } fileLst.append(t.viewMode == 'thumbs' ? t.thumbTpl : t.textTpl, r); $('#file_' + i + ' img.thumbnailimage').attr('src', r.thumburl); }); }, deleteFiles : function(fl) { var t = this, args = {}; if (fl) { $(fl).each(function(i, v) { args['path' + i] = v.path; }); $.WindowManager.confirm($.translate('{#view.confirm_delete}'), function(s) { if (s) { if (!t.isDemo()) { RPC.exec('im.deleteFiles', args, function (data) { if (!RPC.handleError({message : '{#error.delete_failed}', visual_path : t.visualPath, response : data})) { t.listFiles(); t.listDirs(); } }); } } }); } }, insertFiles : function() { var t = this, s = t.currentWin.getArgs(), selectedPaths = []; $(t.selectedFiles).each(function(i, v) { selectedPaths.push(v.path); }); RPC.insertFiles({ relative_urls : s.relative_urls, document_base_url : s.document_base_url, default_base_url : s.default_base_url, no_host : s.remove_script_host || s.no_host, paths : selectedPaths, progress_message : $.translate("{#common.image_data}"), insert_filter : s.insert_filter, oninsert : function(o) { t.currentWin.close(); if (s.oninsert) { $(o.files).each(function(i, v) { if (v.path == t.focusedFile.path) o.focusedFile = v; }); s.oninsert(o); } } }); }, editFile : function(f) { $('#center').hide(); window.scrollTo(0, 0); $.WindowManager.open({ url : 'edit.html' + this.urlSuffix, onclose : function() { $('#center').show(); } }, { is_demo : this.demoMode, path : this.focusedFile.path, visual_path : this.visualPath, onsave : function() { ImageManager.listFiles(); ImageManager.listDirs(); } }).maximize(); }, viewFile : function(f) { $('#center').hide(); window.scrollTo(0, 0); $.WindowManager.open({ url : 'view.html' + this.urlSuffix, chromeless : 1, onclose : function() { $('#center').show(); } }, { is_demo : this.demoMode, path : f.path, visual_path : this.visualPath, ondelete : function() { ImageManager.listFiles(); } }).maximize(); }, createDir : function() { $.WindowManager.open({ url : 'createdir.html' + this.urlSuffix, width : 450, height : 280 }, { is_demo : this.demoMode, path : this.path, visual_path : this.visualPath, oncreate : function() { ImageManager.listFiles(); ImageManager.listDirs(); } }); }, uploadFiles : function() { $.WindowManager.open({ url : 'upload.html' + this.urlSuffix, width : 550, height : 350, scrolling : 'no' }, { is_demo : this.demoMode, path : this.path, visual_path : this.visualPath, onupload : function() { ImageManager.listFiles(); } }); }, fileManager : function() { var suf; if (this.fileManagerURL.indexOf('?') != -1) suf = this.urlSuffix.replace(/\?/, '&'); document.location = this.fileManagerURL + suf; }, listRoots : function() { var t = this; if (t.rootPathName) { $('#category_list').html(t.caregoryListTpl, {name : t.rootPathName, path : t.rootPath}); return; } RPC.exec('im.listFiles', { "path" : "root:///" }, function(data) { $(RPC.toArray(data.result)).each(function() { $('#category_list').append(t.caregoryListTpl, this); }); }); }, listDirs : function() { var t = this; $('#folder_list').html($.translate('<li class="progress">{#common.loading}</li>')); RPC.exec('im.listFiles', { path : t.path, root_path : t.rootPath, only_dirs : true, include_directory_pattern : t.include_directory_pattern, exclude_directory_pattern : t.exclude_directory_pattern, filter : t.filter, remember_last_path : t.remember_last_path }, function(data) { $('#folder_list').html(''); $(RPC.toArray(data.result)).each(function() { $('#folder_list').append(t.caregoryListTpl, this); }); }); } }); $(function() { ImageManager.init(); ImageManager.listFiles(); ImageManager.listDirs(); ImageManager.listRoots(); }); })(jQuery);
JavaScript
// Copyright 2007, Google Inc. // // Redistribution and use in source and binary forms, with or without // modification, are permitted provided that the following conditions are met: // // 1. Redistributions of source code must retain the above copyright notice, // this list of conditions and the following disclaimer. // 2. Redistributions in binary form must reproduce the above copyright notice, // this list of conditions and the following disclaimer in the documentation // and/or other materials provided with the distribution. // 3. Neither the name of Google Inc. nor the names of its contributors may be // used to endorse or promote products derived from this software without // specific prior written permission. // // THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS OR IMPLIED // WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF // MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO // EVENT SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, // SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, // PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; // OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, // WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR // OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF // ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. // // Sets up google.gears.*, which is *the only* supported way to access Gears. // // Circumvent this file at your own risk! // // In the future, Gears may automatically define google.gears.* without this // file. Gears may use these objects to transparently fix bugs and compatibility // issues. Applications that use the code below will continue to work seamlessly // when that happens. (function() { // We are already defined. Hooray! if (window.google && google.gears) { return; } var factory = null; // Firefox if (typeof GearsFactory != 'undefined') { factory = new GearsFactory(); } else { // IE try { factory = new ActiveXObject('Gears.Factory'); // privateSetGlobalObject is only required and supported on WinCE. if (factory.getBuildInfo().indexOf('ie_mobile') != -1) { factory.privateSetGlobalObject(this); } } catch (e) { // Safari if ((typeof navigator.mimeTypes != 'undefined') && navigator.mimeTypes["application/x-googlegears"]) { factory = document.createElement("object"); factory.style.display = "none"; factory.width = 0; factory.height = 0; factory.type = "application/x-googlegears"; document.documentElement.appendChild(factory); } } } // *Do not* define any objects if Gears is not installed. This mimics the // behavior of Gears defining the objects in the future. if (!factory) { return; } // Now set up the objects, being careful not to overwrite anything. // // Note: In Internet Explorer for Windows Mobile, you can't add properties to // the window object. However, global objects are automatically added as // properties of the window object in all browsers. if (!window.google) { google = {}; } if (!google.gears) { google.gears = {factory: factory}; } })();
JavaScript
var PNG = { isOldIE : navigator.userAgent.indexOf('MSIE 5') > 0 || navigator.userAgent.indexOf('MSIE 6') > 0, transparentImg : 'img/transparent.gif', transparentBGImg : '../img/transparent.gif', fix : function(e) { var rs, cs, b, o; // Remove behavior to prevent memory leaks e.runtimeStyle.behavior = "none"; // Check browser version if (!this.isOldIE) return; // Use old PNG src if (e.png_src) e.src = e.png_src; // Is PNG image if (e.src && e.src.toLowerCase().indexOf('.png') > 0) { e.png_src = e.src; e.runtimeStyle.filter = "progid:DXImageTransform.Microsoft.AlphaImageLoader(src='" + e.src + "', sizingMethod='scale')"; e.src = this.transparentImg; } cs = e.currentStyle; b = cs.backgroundImage; // Has PNG background if (b && b.toLowerCase().indexOf('png') > 0) { rs = e.runtimeStyle; b = b.replace(/url\(\"([^"]+)\"\)/g, "$1"); o = rs["background-position"]; if (!cs.hasLayout) rs.display = 'inline-block'; rs.backgroundImage = 'url(\'' + this.transparentBGImg + '\')'; rs.filter = "progid:DXImageTransform.Microsoft.AlphaImageLoader(src='" + b + "', sizingMethod='crop')"; rs["background-position"] = o; } // Remove referenced to prevent memory leaks rs = cs = b = o = e = null; } };
JavaScript
(function($){ window.UploadDialog = { currentWin : $.WindowManager.find(window), init : function() { var t = this, args; t.args = args = $.extend({ path : '{default}', visual_path : '/' }, t.currentWin.getArgs()); t.fileListTpl = $.templateFromScript('#filelist_item_template'); $('.uploadtype').html($.translate('{#upload.basic_upload}', 0, {a : '<a id="singleupload" href="#basic">', '/a' : '</a>'})); $('#createin').html(args.visual_path); $('form input[name=path]').val(args.path); $('form input[name=file0]').change(function(e) { $('form input[name=name0]').val(t.cleanName(/([^\/\\]+)$/.exec(e.target.value)[0].replace(/\.[^\.]+$/, ''))); }); $('form').submit(function() { $.WindowManager.showProgress({message : $.translate('{#upload.progress}')}); }); if (document.location.hostname != document.domain) $('form input[name=domain]').val(document.domain); t.path = args.path; $('#singleupload').click(function(e) { $('#multiupload_view').hide(); $('#singleupload_view').show(); }); RPC.exec('im.getConfig', {path : args.path}, function(data) { var config = data.result, maxSize, upExt, fsExt, outExt = [], i, x, found; maxSize = config['upload.maxsize']; fsExt = config['filesystem.extensions'].split(','); upExt = config['upload.extensions'].split(','); t.debug = config['general.debug'] == "true"; t.shouldCleanNames = config['filesystem.clean_names'] == "true"; t.chunkSize = config['upload.chunk_size'] || '1mb'; $('#content').show(); if ($.multiUpload.initialized) $('#multiupload_view').show(); else $('#singleupload_view').show(); // Disabled upload if (config['upload.multiple_upload'] != "true") { $('#multiupload_view').hide(); $('#singleupload_view').show(); } maxSize = maxSize.replace(/\s+/, ''); maxSize = maxSize.replace(/([0-9]+)/g, '$1 '); if (upExt[0] == '*') upExt = fsExt; if (fsExt[0] == '*') fsExt = upExt; for (i = 0; i < upExt.length; i++) { upExt[i] = $.trim(upExt[i].toLowerCase()); found = false; for (x = 0; x < fsExt.length; x++) { fsExt[x] = $.trim(fsExt[x]).toLowerCase(); if (upExt[i] == fsExt[x]) { found = true; break; } } if (found) outExt.push(upExt[i]); } t.validExtensions = outExt; t.maxSize = maxSize; $('#facts').html($.templateFromScript('#facts_template'), {extensions : outExt.join(', '), maxsize : maxSize, path : args.visual_path}); if (config['upload.multiple_upload'] == "true") t.initMultiUpload(); }); $('#cancel').click(function() {t.currentWin.close();}); }, cleanName : function(s) { if (this.shouldCleanNames) s = $.cleanName(s); return s; }, handleSingleUploadResponse : function(data) { var t = this, args = t.currentWin.getArgs(); $.WindowManager.hideProgress(); if (!RPC.handleError({message : '{#error.upload_failed}', visual_path : t.args.visual_path, response : data})) { var res = RPC.toArray(data.result); $.WindowManager.info($.translate('{#message.upload_ok}')); $('#file0, #name0').val(''); t.insertFiles([res[0].file]); } }, initMultiUpload : function() { var t = this, up, args = t.currentWin.getArgs(), initial = 1, startTime; up = $.multiUpload.create({ silverlight_xap_url : '../../stream/index.php?theme=im&package=static_files&file=multiupload_xap', upload_url : '../../stream/index.php?cmd=im.upload', path : t.path, filter : t.validExtensions, chunk_size : t.chunkSize, max_size : t.maxSize, flash_browse_button : '#add', oninit : function() { $('#add').removeClass('hidden'); } }); if (t.debug) alert('Runtime used: ' + $.multiUpload.runtime); function calc(up) { var size = 0, uploaded = 0, loaded = 0, unloaded = 0, bps = 0, finished = true, fl = []; if (!up.files.length) { $('#selectview').css('top', 0); $('#selectview').show(); $('#fileblock').css({position : 'relative', top : 400}); initial = 1; return; } $(up.files).each(function(i, f) { size += f.size; loaded += f.loaded; if (f.status == 'completed') uploaded++; if (!f.status) finished = false; }); bps = Math.ceil(loaded / ((new Date().getTime() - startTime || 1) / 1000.0)); if (finished) { $('#abortupload').hide(); $(up.files).each(function(i, f) { if (f.status == 'completed') fl.push(t.path + '/' + f.name); }); t.insertFiles(fl); $('#progressbar').css('width', '100%'); return; } $('#progressinfo').html($.translate('{#upload.progressinfo}', 1, {loaded : up.formatSize(loaded), total : up.formatSize(size), speed : up.formatSize(bps)})); $('#progressbar').css('width', Math.round(loaded / size * 100.0) + '%'); $('#stats').html($.translate('{#upload.statusrow}', 1, {files : up.files.length, size : up.formatSize(size)})); }; // Register event listeners $(up).bind('multiUpload:filesSelected', function(e, fs) { var up = this, totalSize = 0; if (!fs.files.length) { $.WindowManager.info($.translate('{#upload.no_valid_files}')); return; } if (initial) { $('#selectview').animate({ top: '-150px' }, 1000); $('#fileblock').animate({ top:'-60px' }, 1000, 'linear', function() { $('#fileblock').css('position', 'static'); $('#selectview').hide(); up.repaint(); }); initial = 0; } $(fs.files).each(function(i, fo) { fo.name = t.cleanName(fo.name); $('#files').show(); $('#files tbody').append(t.fileListTpl, {id : fo.id, name : fo.name, size : fo.size}); $('#' + fo.id + ' a.remove').click(function(e) { $('#' + fo.id).remove(); $.multiUpload.get(up.id).removeFile(fo.id); e.preventDefault(); return false; }); $('#' + fo.id + ' a.rename').click(function(e) { var a = $(e.target), inp, parts; if (!a.hasClass('disabled')) { parts = /^(.+)(\.[^\.]+)$/.exec(fo.name); a.hide(); $(e.target).parent().append('<input id="rename" type="text" class="text" />'); inp = $('#rename').val(parts[1]); t.renameEnabled = 1; inp.focus().blur(function() { t.endRename(); }).keydown(function(e) { var c = e.keyCode; if (c == 13 || c == 27) { if (c == 13) { fo.name = t.cleanName(inp.val()) + parts[2]; a.html(fo.name); } t.endRename(); } }); } e.preventDefault(); return false; }); }); up.settings.flash_browse_button = '#addmore'; up.repaint(); $('#filelist')[0].scrollTop = 0; }); $(up).bind('multiUpload:fileUploaded', function(e, o) { $('#' + o.file.id).removeClass('failed').addClass('done'); }); $(up).bind('multiUpload:filesChanged', function() { calc(up); up.repaint(); t.endRename(); }); $(up).bind('multiUpload:fileUploadProgress', function(e, pr) { if (up.status) { if (!pr.file.scroll) { $('#filelist').scrollTo($('#' + pr.file.id), 50); pr.file.scroll = 1; } $('#' + pr.file.id + ' td.status').html(Math.round(pr.loaded / pr.total * 100.0) + '%'); calc(up); } }); $(up).bind('multiUpload:chunkUploaded', function(e, o) { var res = $.parseJSON(o.response), data = RPC.toArray(res.result); if (data[0]["status"] != 'OK') { o.file.loaded = o.file.size; calc(up); $('#' + o.file.id).addClass('failed'); $('#' + o.file.id + ' td.status').html($.translate(data[0]["message"])); o.cancel = 1; } }); $(up).bind('multiUpload:uploadChunkError', function(e, o) { $('#' + o.file.id).addClass('failed'); $('#' + o.file.id + ' td.status').html('Failed').attr('title', o.error); //top.console.log(o.file, o.chunk, o.chunks, o.error); }); // Add UI events $('#add, #addmore').click(function(e) { up.selectFiles(); e.preventDefault(); return false; }); $('#abortupload').click(function(e) { up.stopUpload(); $.WindowManager.info($.translate('{#upload.cancelled}'), function() { t.currentWin.close(); }); }); $('#uploadstart').click(function(e) { $('#uploadstart').parent().hide(); $('#status').show(); $('#statsrow').hide(); $('#files .status').html('-'); $('#files .fname a').addClass('disabled'); startTime = new Date().getTime(); up.startUpload(); e.preventDefault(); return false; }); $('#uploadstop').click(function(e) { up.stopUpload(); e.preventDefault(); return false; }); $('#clear').click(function(e) { up.clearFiles(); $('#files').hide(); $('#files tbody').html(''); e.preventDefault(); return false; }); }, insertFiles : function(pa) { var s = this.currentWin.getArgs(); // Insert file if (s.onupload) { RPC.insertFiles({ relative_urls : s.relative_urls, document_base_url : s.document_base_url, default_base_url : s.default_base_url, no_host : s.remove_script_host || s.no_host, paths : pa, insert_filter : s.insert_filter, oninsert : function(o) { s.onupload(o); } }); } }, isDemo : function() { if (this.currentWin.getArgs().is_demo) { $.WindowManager.info($.translate('{#error.demo}')); return true; } }, endRename : function() { if (this.renameEnabled) { $('#files input').remove(); $('#files a').show(); this.renameEnabled = 0; } } }; // JSON handler window.handleJSON = function(data) { window.focus(); UploadDialog.handleSingleUploadResponse(data); }; $(function(e) { UploadDialog.init(); }); })(jQuery);
JavaScript
(function ($) { var m = { '\b': '\\b', '\t': '\\t', '\n': '\\n', '\f': '\\f', '\r': '\\r', '"' : '\\"', '\\': '\\\\' }, s = { 'array': function (x) { var a = ['['], b, f, i, l = x.length, v; for (i = 0; i < l; i += 1) { v = x[i]; f = s[typeof v]; if (f) { v = f(v); if (typeof v == 'string') { if (b) { a[a.length] = ','; } a[a.length] = v; b = true; } } } a[a.length] = ']'; return a.join(''); }, 'boolean': function (x) { return String(x); }, 'null': function (x) { return "null"; }, 'number': function (x) { return isFinite(x) ? String(x) : 'null'; }, 'object': function (x) { if (x) { if (x instanceof Array) { return s.array(x); } var a = ['{'], b, f, i, v; for (i in x) { v = x[i]; f = s[typeof v]; if (f) { v = f(v); if (typeof v == 'string') { if (b) { a[a.length] = ','; } a.push(s.string(i), ':', v); b = true; } } } a[a.length] = '}'; return a.join(''); } return 'null'; }, 'string': function (x) { if (/["\\\x00-\x1f]/.test(x)) { x = x.replace(/([\x00-\x1f\\"])/g, function(a, b) { var c = m[b]; if (c) { return c; } c = b.charCodeAt(); return '\\u00' + Math.floor(c / 16).toString(16) + (c % 16).toString(16); }); } return '"' + x + '"'; } }; $.toJSON = function(v) { var f = isNaN(v) ? s[typeof v] : s['number']; if (f) return f(v); }; $.parseJSON = function(v, safe) { if (safe === undefined) safe = $.parseJSON.safe; if (safe && !/^("(\\.|[^"\\\n\r])*?"|[,:{}\[\]0-9.\-+Eaeflnr-u \n\r\t])+?$/.test(v)) return undefined; return eval('('+v+')'); }; $.parseJSON.safe = false; })(jQuery);
JavaScript
/** * jQuery.ScrollTo * Copyright (c) 2007-2008 Ariel Flesler - aflesler(at)gmail(dot)com | http://flesler.blogspot.com * Dual licensed under MIT and GPL. * Date: 9/11/2008 * * @projectDescription Easy element scrolling using jQuery. * http://flesler.blogspot.com/2007/10/jqueryscrollto.html * Tested with jQuery 1.2.6. On FF 2/3, IE 6/7, Opera 9.2/5 and Safari 3. on Windows. * * @author Ariel Flesler * @version 1.4 * * @id jQuery.scrollTo * @id jQuery.fn.scrollTo * @param {String, Number, DOMElement, jQuery, Object} target Where to scroll the matched elements. * The different options for target are: * - A number position (will be applied to all axes). * - A string position ('44', '100px', '+=90', etc ) will be applied to all axes * - A jQuery/DOM element ( logically, child of the element to scroll ) * - A string selector, that will be relative to the element to scroll ( 'li:eq(2)', etc ) * - A hash { top:x, left:y }, x and y can be any kind of number/string like above. * @param {Number} duration The OVERALL length of the animation, this argument can be the settings object instead. * @param {Object,Function} settings Optional set of settings or the onAfter callback. * @option {String} axis Which axis must be scrolled, use 'x', 'y', 'xy' or 'yx'. * @option {Number} duration The OVERALL length of the animation. * @option {String} easing The easing method for the animation. * @option {Boolean} margin If true, the margin of the target element will be deducted from the final position. * @option {Object, Number} offset Add/deduct from the end position. One number for both axes or { top:x, left:y }. * @option {Object, Number} over Add/deduct the height/width multiplied by 'over', can be { top:x, left:y } when using both axes. * @option {Boolean} queue If true, and both axis are given, the 2nd axis will only be animated after the first one ends. * @option {Function} onAfter Function to be called after the scrolling ends. * @option {Function} onAfterFirst If queuing is activated, this function will be called after the first scrolling ends. * @return {jQuery} Returns the same jQuery object, for chaining. * * @desc Scroll to a fixed position * @example $('div').scrollTo( 340 ); * * @desc Scroll relatively to the actual position * @example $('div').scrollTo( '+=340px', { axis:'y' } ); * * @dec Scroll using a selector (relative to the scrolled element) * @example $('div').scrollTo( 'p.paragraph:eq(2)', 500, { easing:'swing', queue:true, axis:'xy' } ); * * @ Scroll to a DOM element (same for jQuery object) * @example var second_child = document.getElementById('container').firstChild.nextSibling; * $('#container').scrollTo( second_child, { duration:500, axis:'x', onAfter:function(){ * alert('scrolled!!'); * }}); * * @desc Scroll on both axes, to different values * @example $('div').scrollTo( { top: 300, left:'+=200' }, { axis:'xy', offset:-20 } ); */ ;(function( $ ){ var $scrollTo = $.scrollTo = function( target, duration, settings ){ $(window).scrollTo( target, duration, settings ); }; $scrollTo.defaults = { axis:'y', duration:1 }; // Returns the element that needs to be animated to scroll the window. // Kept for backwards compatibility (specially for localScroll & serialScroll) $scrollTo.window = function( scope ){ return $(window).scrollable(); }; // Hack, hack, hack... stay away! // Returns the real elements to scroll (supports window/iframes, documents and regular nodes) $.fn.scrollable = function(){ return this.map(function(){ // Just store it, we might need it var win = this.parentWindow || this.defaultView, // If it's a document, get its iframe or the window if it's THE document elem = this.nodeName == '#document' ? win.frameElement || win : this, // Get the corresponding document doc = elem.contentDocument || (elem.contentWindow || elem).document, isWin = elem.setInterval; return elem.nodeName == 'IFRAME' || isWin && $.browser.safari ? doc.body : isWin ? doc.documentElement : this; }); }; $.fn.scrollTo = function( target, duration, settings ){ if( typeof duration == 'object' ){ settings = duration; duration = 0; } if( typeof settings == 'function' ) settings = { onAfter:settings }; settings = $.extend( {}, $scrollTo.defaults, settings ); // Speed is still recognized for backwards compatibility duration = duration || settings.speed || settings.duration; // Make sure the settings are given right settings.queue = settings.queue && settings.axis.length > 1; if( settings.queue ) // Let's keep the overall duration duration /= 2; settings.offset = both( settings.offset ); settings.over = both( settings.over ); return this.scrollable().each(function(){ var elem = this, $elem = $(elem), targ = target, toff, attr = {}, win = $elem.is('html,body'); switch( typeof targ ){ // A number will pass the regex case 'number': case 'string': if( /^([+-]=)?\d+(px)?$/.test(targ) ){ targ = both( targ ); // We are done break; } // Relative selector, no break! targ = $(targ,this); case 'object': // DOMElement / jQuery if( targ.is || targ.style ) // Get the real position of the target toff = (targ = $(targ)).offset(); } $.each( settings.axis.split(''), function( i, axis ){ var Pos = axis == 'x' ? 'Left' : 'Top', pos = Pos.toLowerCase(), key = 'scroll' + Pos, old = elem[key], Dim = axis == 'x' ? 'Width' : 'Height', dim = Dim.toLowerCase(); if( toff ){// jQuery / DOMElement attr[key] = toff[pos] + ( win ? 0 : old - $elem.offset()[pos] ); // If it's a dom element, reduce the margin if( settings.margin ){ attr[key] -= parseInt(targ.css('margin'+Pos)) || 0; attr[key] -= parseInt(targ.css('border'+Pos+'Width')) || 0; } attr[key] += settings.offset[pos] || 0; if( settings.over[pos] ) // Scroll to a fraction of its width/height attr[key] += targ[dim]() * settings.over[pos]; }else attr[key] = targ[pos]; // Number or 'number' if( /^\d+$/.test(attr[key]) ) // Check the limits attr[key] = attr[key] <= 0 ? 0 : Math.min( attr[key], max(Dim) ); // Queueing axes if( !i && settings.queue ){ // Don't waste time animating, if there's no need. if( old != attr[key] ) // Intermediate animation animate( settings.onAfterFirst ); // Don't animate this axis again in the next iteration. delete attr[key]; } }); animate( settings.onAfter ); function animate( callback ){ $elem.animate( attr, duration, settings.easing, callback && function(){ callback.call(this, target, settings); }); }; function max( Dim ){ var attr ='scroll'+Dim, doc = elem.ownerDocument; return win ? Math.max( doc.documentElement[attr], doc.body[attr] ) : elem[attr]; }; }).end(); }; function both( val ){ return typeof val == 'object' ? val : { top:val, left:val }; }; })( jQuery );
JavaScript
/** * jQuery Templates * * Dual licensed under the MIT (http://www.opensource.org/licenses/mit-license.php) * and GPL (http://www.opensource.org/licenses/gpl-license.php) licenses. * * Written by: Stan Lemon <stanlemon@mac.com> * * Based off of the Ext.Template library, available at: * http://www.extjs.com * * This library provides basic templating functionality, allowing for macro-based * templates within jQuery. * * Basic Usage: * * var t = $.template('<div id="foo">Hello ${name}, how are you ${question}? I am ${me:substr(0,10)}</div>'); * * $(selector).append( t , { * name: 'Stan', * question: 'feeling', * me: 'doing quite well myself, thank you very much!' * }); * * Requires: jQuery 1.2+ * * * @todo Add callbacks to the DOM manipulation methods, so that events can be bound * to template nodes after creation. */ (function($){ /** * Create a New Template */ $.template = function(html, options) { return new $.template.instance(html, options); }; /** * Template constructor - Creates a new template instance. * * @param html The string of HTML to be used for the template. * @param options An object of configurable options. Currently * you can toggle compile as a boolean value and set a custom * template regular expression on the property regx by * specifying the key of the regx to use from the regx object. */ $.template.instance = function(html, options) { // If a custom regular expression has been set, grab it from the regx object if ( options && options['regx'] ) options.regx = this.regx[ options.regx ]; this.options = $.extend({ compile: false, regx: this.regx.standard }, options || {}); this.html = html; if (this.options.compile) { this.compile(); } this.isTemplate = true; }; /** * Regular Expression for Finding Variables * * The default pattern looks for variables in JSP style, the form of: ${variable} * There are also regular expressions available for ext-style variables and * jTemplate style variables. * * You can add your own regular expressions for variable ussage by doing. * $.extend({ $.template.re , { * myvartype: /...../g * } * * Then when creating a template do: * var t = $.template("<div>...</div>", { regx: 'myvartype' }); */ $.template.regx = $.template.instance.prototype.regx = { jsp: /\$\{([\w-]+)(?:\:([\w\.]*)(?:\((.*?)?\))?)?\}/g, ext: /\{([\w-]+)(?:\:([\w\.]*)(?:\((.*?)?\))?)?\}/g, jtemplates: /\{\{([\w-]+)(?:\:([\w\.]*)(?:\((.*?)?\))?)?\}\}/g }; /** * Set the standard regular expression to be used. */ $.template.regx.standard = $.template.regx.jsp; /** * Variable Helper Methods * * This is a collection of methods which can be used within the variable syntax, ie: * ${variable:substr(0,30)} Which would only print a substring, 30 characters in length * begining at the first character for the variable named "variable". * * A basic substring helper is provided as an example of how you can define helpers. * To add more helpers simply do: * $.extend( $.template.helpers , { * sampleHelper: function() { ... } * }); */ $.template.helpers = $.template.instance.prototype.helpers = { substr : function(value, start, length){ return String(value).substr(start, length); } }; /** * Template Instance Methods */ $.extend( $.template.instance.prototype, { /** * Apply Values to a Template * * This is the macro-work horse of the library, it receives an object * and the properties of that objects are assigned to the template, where * the variables in the template represent keys within the object itself. * * @param values An object of properties mapped to template variables */ apply: function(values) { if (this.options.compile) { return this.compiled(values); } else { var tpl = this; var fm = this.helpers; var fn = function(m, name, format, args) { if (format) { if (format.substr(0, 5) == "this."){ return tpl.call(format.substr(5), values[name], values); } else { if (args) { // quoted values are required for strings in compiled templates, // but for non compiled we need to strip them // quoted reversed for jsmin var re = /^\s*['"](.*)["']\s*$/; args = args.split(','); for(var i = 0, len = args.length; i < len; i++) { args[i] = args[i].replace(re, "$1"); } args = [values[name]].concat(args); } else { args = [values[name]]; } return fm[format].apply(fm, args); } } else { return values[name] !== undefined ? values[name] : ""; } }; return this.html.replace(this.options.regx, fn); } }, /** * Compile a template for speedier usage */ compile: function() { var sep = $.browser.mozilla ? "+" : ","; var fm = this.helpers; var fn = function(m, name, format, args){ if (format) { args = args ? ',' + args : ""; if (format.substr(0, 5) != "this.") { format = "fm." + format + '('; } else { format = 'this.call("'+ format.substr(5) + '", '; args = ", values"; } } else { args= ''; format = "(values['" + name + "'] == undefined ? '' : "; } return "'"+ sep + format + "values['" + name + "']" + args + ")"+sep+"'"; }; var body; if ($.browser.mozilla) { body = "this.compiled = function(values){ return '" + this.html.replace(/\\/g, '\\\\').replace(/(\r\n|\n)/g, '\\n').replace(/'/g, "\\'").replace(this.options.regx, fn) + "';};"; } else { body = ["this.compiled = function(values){ return ['"]; body.push(this.html.replace(/\\/g, '\\\\').replace(/(\r\n|\n)/g, '\\n').replace(/'/g, "\\'").replace(this.options.regx, fn)); body.push("'].join('');};"); body = body.join(''); } eval(body); return this; } }); /** * Save a reference in this local scope to the original methods which we're * going to overload. **/ var $_old = { domManip: $.fn.domManip, text: $.fn.text, html: $.fn.html }; /** * Overwrite the domManip method so that we can use things like append() by passing a * template object and macro parameters. */ $.fn.domManip = function( args, table, reverse, callback ) { if (args[0].isTemplate) { // Apply the template and it's arguments... args[0] = args[0].apply( args[1] ); // Get rid of the arguements, we don't want to pass them on delete args[1]; } // Call the original method var r = $_old.domManip.apply(this, arguments); return r; }; /** * Overwrite the html() method */ $.fn.html = function( value , o ) { if (value && value.isTemplate) var value = value.apply( o ); var r = $_old.html.apply(this, [value]); return r; }; /** * Overwrite the text() method */ $.fn.text = function( value , o ) { if (value && value.isTemplate) var value = value.apply( o ); var r = $_old.text.apply(this, [value]); return r; }; })(jQuery);
JavaScript
(function($){ window.CreateDirDialog = { currentWin : $.WindowManager.find(window), init : function() { var t = this, args, cleanNames; args = $.extend({ path : '{default}', visual_path : '/' }, t.currentWin.getArgs()); // Add templates RPC.exec('im.getConfig', {path : args.path}, function(data) { var config = data.result, templates = [], tpl; if (!RPC.handleError({message : 'Get config error', visual_path : t.visualPath, response : data})) { cleanNames = config['filesystem.clean_names'] == "true"; $(config['filesystem.directory_templates'].split(/,/)).each(function(i, v) { if (v) { v = $.trim(v).split('='); templates.push({name : /([^\/]+)$/.exec(v[0])[0], value : v[1] || v[0]}); } }); if (config['filesystem.force_directory_template'] == "true") { $('#template').html(''); if (templates.length == 1) $('#templaterow').hide(); } if (templates.length == 0) $('#templaterow').hide(); tpl = $.templateFromScript('#template_template'); $(templates).each(function(i, v) { $('#template').append(tpl, v); }); $('#content').show(); $('#createin').html(args.visual_path); $('form').submit(function() { var tpl = $('#template').val(), name = $('#dirname').val(); if (cleanNames) name = $.cleanName(name); if (!t.isDemo()) { RPC.exec('im.createDirs', {path : args.path, name0 : name, template0 : tpl}, function(data) { var res = RPC.toArray(data.result), s = t.currentWin.getArgs(); if (!RPC.handleError({message : '{#error.createdir_failed}', visual_path : args.visual_path, response : data})) { // Insert file if (s.oncreate) { RPC.insertFile({ relative_urls : s.relative_urls, document_base_url : s.document_base_url, default_base_url : s.default_base_url, no_host : s.remove_script_host || s.no_host, path : res[0].file, progress_message : $.translate("{#message.insert}"), insert_filter : s.insert_filter, oninsert : function(o) { s.oncreate(o); t.currentWin.close(); } }); } } }); } return false; }); $('#cancel').click(function() {t.currentWin.close();}); } }); }, isDemo : function() { if (this.currentWin.getArgs().is_demo) { $.WindowManager.info($.translate('{#error.demo}')); return true; } } }; $(function() { CreateDirDialog.init(); }); })(jQuery);
JavaScript
(function($){ window.ViewDialog = { currentWin : $.WindowManager.find(window), init : function() { var t = this, args; t.args = args = $.extend({ path : '{default}', visual_path : '/' }, t.currentWin.getArgs()); // Compile templates t.singeViewTpl = $.templateFromScript('#singleview_template'); t.mpgTpl = $.templateFromScript('#mpg_template'); t.rmTpl = $.templateFromScript('#rm_template'); t.movTpl = $.templateFromScript('#mov_template'); t.dcrTpl = $.templateFromScript('#dcr_template'); t.footerFullTpl = $.templateFromScript('#single_footer_full'); t.footerNoEditTpl = $.templateFromScript('#single_footer_no_edit'); t.footerSimpleTpl = $.templateFromScript('#single_footer_simple'); $('#prev').click(function(e) { if (!$(e.target).hasClass('disabled')) t.getMediaInfo(t.prevMedia); }); $('#next').click(function(e) { if (!$(e.target).hasClass('disabled')) t.getMediaInfo(t.nextMedia); }); $('#gallery').click(function(e) { if (!$(e.target).hasClass('disabled')) t.currentWin.close(); }); $('#singlefooter').click(function(e) { var el = e.target, a = el.nodeName == 'A' ? el : $(el).parents('a')[0]; if (a) { a = $(a); if (a.attr('id') == 'deleteit' && !a.hasClass('disabled')) t.deleteFile(t.path); if (a.attr('id') == 'edit' && !a.hasClass('disabled')) t.editFile(t.path); } }); $().keydown(function(e) { switch (e.keyCode) { case 32: // space case 110: // n case 34: // page down case 39: // right arrow case 40: // down arrow t.getMediaInfo(t.nextMedia); break; case 102: // p case 33: // page up case 37: // left arrow case 38: // up arrow t.getMediaInfo(t.prevMedia); break; case 27: // Esc t.currentWin.close(); break; } }); $(window).bind('resize', function() { t.resizeView(); }); $('#singlecontent').click(function(e) { if (e.target.nodeName == 'IMG' && $(e.target).hasClass('viewimage')) { if (args.onselect) { RPC.insertFile({ relative_urls : args.relative_urls, document_base_url : s.document_base_url, default_base_url : s.default_base_url, no_host : args.remove_script_host || args.no_host, path : t.path, progress_message : $.translate("{#message.insert}"), insert_filter : args.insert_filter, oninsert : function(o) { args.onselect(o); t.currentWin.close(); } }); } else t.currentWin.close(); } }); t.getMediaInfo(args.path); focus(); }, getMediaInfo : function(p) { var t = this; t.path = p; RPC.exec('im.getMediaInfo', {path : p}, function (data) { var res, row, tpl, footTpl; res = RPC.toArray(data.result); row = res[0]; t.nextMedia = row.next; t.prevMedia = row.prev; if (!row.next) $('#next').addClass('disabled'); else $('#next').removeClass('disabled'); if (!row.prev) $('#prev').addClass('disabled'); else $('#prev').removeClass('disabled'); footTpl = t.footerSimpleTpl; switch (row.type) { case "jpg": case "jpeg": case "gif": case "png": case "bmp": tpl = t.singeViewTpl; footTpl = t.footerFullTpl; break; case "mpg": case "mpeg": case "wma": case "wmv": case "asf": case "avi": tpl = t.mpgTpl; break; case "qt": case "mov": tpl = t.movTpl; break; case "rm": case "ram": tpl = t.rmTpl; break; case "dcr": tpl = t.dcrTpl; break; case "swf": var so = new SWFObject("../../stream/index.php?cmd=im.streamFile&path="+ escape(row.path), "swfMovie", row.width, row.height, "7", "#FFFFFF"); so.addParam("quality", "high"); so.addParam("scale", "showall"); so.addParam("wmode", "transparent"); so.write("singlecontent"); $('#singlefooter').html(t.footerNoEditTpl, row); return; case "flv": var so = new SWFObject("flvplayer/flvPlayer.swf", "flvPlayer", row.width, row.height, "8", "#FFFFFF"); so.addVariable("flvToPlay", "../../../stream/index.php?cmd=im.streamFile%26path=" + escape(row.path)); so.addVariable("hiddenGui", "false"); so.addVariable("showScaleModes", "true"); so.addVariable("autoStart", "false"); so.addParam("allowFullScreen", "true"); so.write("singlecontent"); $('#singlefooter').html(t.footerNoEditTpl, row); return; } $('#singlecontent').html(tpl, row); $('#singlefooter').html(footTpl, row); if (row.custom) { if (!row.custom.editable) $('#singleview .editsingle a.edt').addClass('disabled'); else $('#singleview .editsingle a.edt').removeClass('disabled'); } t.resizeView(); }); }, resizeView : function() { $('#singleimg').css({'width' : $.winWidth() - 60, 'height' : $.winHeight() - 100}); }, deleteFile : function(p) { var t = this; $.WindowManager.confirm($.translate('{#view.confirm_delete}'), function(s) { if (s) { if (!t.isDemo()) { RPC.exec('im.deleteFiles', {path0 : p}, function (data) { var args; if (!RPC.handleError({message : '{#error.delete_failed}', visual_path : t.args.visual_path, response : data})) { if (t.args.ondelete) t.args.ondelete(p); if (t.nextMedia) t.getMediaInfo(t.nextMedia); else if (t.prevMedia) t.getMediaInfo(t.prevMedia); else t.currentWin.close(); } }); } } }); }, editFile : function(p) { var t = this; $.WindowManager.open({ url : 'edit.html' }, { is_demo : t.args.is_demo, path : p, visual_path : this.visualPath, onsave : function() { t.getMediaInfo(t.path); } }).maximize(); }, isDemo : function() { if (this.args.is_demo) { $.WindowManager.info($.translate('{#error.demo}')); return true; } } }; $(function(e) { ViewDialog.init(); }); })(jQuery);
JavaScript
(function($){ var man = window.FileManager || window.ImageManager; man.addSpecialFolder({title : '{#history.special_folder_title}', path : 'history:///', type : 'history'}); $().bind('filelist:changed', function() { if (man.path.indexOf('history://') != -1) { $(man.tools).each(function(i, v) { man.setDisabled(v, 1); }); $(['insert', 'download', 'view']).each(function(i, v) { man.setDisabled(v, 0); }); } }); })(jQuery);
JavaScript
(function($){ var man = window.FileManager || window.ImageManager, type = window.FileManager ? 'fm' : 'im'; man.addSpecialFolder({title : '{#favorites.special_folder_title}', path : 'favorite:///', type : 'favorites'}); // Add menu items to context menu $().bind('DropMenu:beforeshow', function(e, m) { if (man.path.indexOf('://') == -1) { m.addSeparator(); m.add({title : $.translate('{#favorites.addfavorites}'), disabled : man.isDisabled('addfavorites') || !man.selectedFiles.length, onclick : addFavorites}); } if (man.path.indexOf('favorite://') != -1) { m.addSeparator(); m.add({title : $.translate('{#favorites.removefavorites}'), disabled : man.isDisabled('removefavorites') || !man.selectedFiles.length, onclick : removeFavorites}); } }); $().bind('filelist:changed', function() { if (man.path.indexOf('favorite://') != -1) { $(man.tools).each(function(i, v) { man.setDisabled(v, 1); }); } }); function addFavorites() { var args = {}; $(man.selectedFiles).each(function(i, f) { args['path' + i] = f.path; }); RPC.exec(type + '.addFavorites', args, function(data) { RPC.handleError({message : '{#error.addfavorites_failed}', visual_path : args.visual_path, response : data}); }); }; function removeFavorites() { var args = {}; $(man.selectedFiles).each(function(i, f) { args['path' + i] = f.path; }); RPC.exec(type + '.removeFavorites', args, function(data) { if (!RPC.handleError({message : '{#error.removefavorites_failed}', visual_path : args.visual_path, response : data})) man.listFiles(); }); }; })(jQuery);
JavaScript
tinyMCE.addI18n('en.autosave',{ restore_content: "Restore auto-saved content", warning_message: "If you restore the saved content, you will lose all the content that is currently in the editor.\n\nAre you sure you want to restore the saved content?" });
JavaScript
/** * editor_plugin_src.js * * Copyright 2009, Moxiecode Systems AB * Released under LGPL License. * * License: http://tinymce.moxiecode.com/license * Contributing: http://tinymce.moxiecode.com/contributing * * Adds auto-save capability to the TinyMCE text editor to rescue content * inadvertently lost. This plugin was originally developed by Speednet * and that project can be found here: http://code.google.com/p/tinyautosave/ * * TECHNOLOGY DISCUSSION: * * The plugin attempts to use the most advanced features available in the current browser to save * as much content as possible. There are a total of four different methods used to autosave the * content. In order of preference, they are: * * 1. localStorage - A new feature of HTML 5, localStorage can store megabytes of data per domain * on the client computer. Data stored in the localStorage area has no expiration date, so we must * manage expiring the data ourselves. localStorage is fully supported by IE8, and it is supposed * to be working in Firefox 3 and Safari 3.2, but in reality is is flaky in those browsers. As * HTML 5 gets wider support, the AutoSave plugin will use it automatically. In Windows Vista/7, * localStorage is stored in the following folder: * C:\Users\[username]\AppData\Local\Microsoft\Internet Explorer\DOMStore\[tempFolder] * * 2. sessionStorage - A new feature of HTML 5, sessionStorage works similarly to localStorage, * except it is designed to expire after a certain amount of time. Because the specification * around expiration date/time is very loosely-described, it is preferrable to use locaStorage and * manage the expiration ourselves. sessionStorage has similar storage characteristics to * localStorage, although it seems to have better support by Firefox 3 at the moment. (That will * certainly change as Firefox continues getting better at HTML 5 adoption.) * * 3. UserData - A very under-exploited feature of Microsoft Internet Explorer, UserData is a * way to store up to 128K of data per "document", or up to 1MB of data per domain, on the client * computer. The feature is available for IE 5+, which makes it available for every version of IE * supported by TinyMCE. The content is persistent across browser restarts and expires on the * date/time specified, just like a cookie. However, the data is not cleared when the user clears * cookies on the browser, which makes it well-suited for rescuing autosaved content. UserData, * like other Microsoft IE browser technologies, is implemented as a behavior attached to a * specific DOM object, so in this case we attach the behavior to the same DOM element that the * TinyMCE editor instance is attached to. */ (function(tinymce) { // Setup constants to help the compressor to reduce script size var PLUGIN_NAME = 'autosave', RESTORE_DRAFT = 'restoredraft', TRUE = true, undefined, unloadHandlerAdded, Dispatcher = tinymce.util.Dispatcher; /** * This plugin adds auto-save capability to the TinyMCE text editor to rescue content * inadvertently lost. By using localStorage. * * @class tinymce.plugins.AutoSave */ tinymce.create('tinymce.plugins.AutoSave', { /** * Initializes the plugin, this will be executed after the plugin has been created. * This call is done before the editor instance has finished it's initialization so use the onInit event * of the editor instance to intercept that event. * * @method init * @param {tinymce.Editor} ed Editor instance that the plugin is initialized in. * @param {string} url Absolute URL to where the plugin is located. */ init : function(ed, url) { var self = this, settings = ed.settings; self.editor = ed; // Parses the specified time string into a milisecond number 10m, 10s etc. function parseTime(time) { var multipels = { s : 1000, m : 60000 }; time = /^(\d+)([ms]?)$/.exec('' + time); return (time[2] ? multipels[time[2]] : 1) * parseInt(time); }; // Default config tinymce.each({ ask_before_unload : TRUE, interval : '30s', retention : '20m', minlength : 50 }, function(value, key) { key = PLUGIN_NAME + '_' + key; if (settings[key] === undefined) settings[key] = value; }); // Parse times settings.autosave_interval = parseTime(settings.autosave_interval); settings.autosave_retention = parseTime(settings.autosave_retention); // Register restore button ed.addButton(RESTORE_DRAFT, { title : PLUGIN_NAME + ".restore_content", onclick : function() { if (ed.getContent().replace(/\s|&nbsp;|<\/?p[^>]*>|<br[^>]*>/gi, "").length > 0) { // Show confirm dialog if the editor isn't empty ed.windowManager.confirm( PLUGIN_NAME + ".warning_message", function(ok) { if (ok) self.restoreDraft(); } ); } else self.restoreDraft(); } }); // Enable/disable restoredraft button depending on if there is a draft stored or not ed.onNodeChange.add(function() { var controlManager = ed.controlManager; if (controlManager.get(RESTORE_DRAFT)) controlManager.setDisabled(RESTORE_DRAFT, !self.hasDraft()); }); ed.onInit.add(function() { // Check if the user added the restore button, then setup auto storage logic if (ed.controlManager.get(RESTORE_DRAFT)) { // Setup storage engine self.setupStorage(ed); // Auto save contents each interval time setInterval(function() { self.storeDraft(); ed.nodeChanged(); }, settings.autosave_interval); } }); /** * This event gets fired when a draft is stored to local storage. * * @event onStoreDraft * @param {tinymce.plugins.AutoSave} sender Plugin instance sending the event. * @param {Object} draft Draft object containing the HTML contents of the editor. */ self.onStoreDraft = new Dispatcher(self); /** * This event gets fired when a draft is restored from local storage. * * @event onStoreDraft * @param {tinymce.plugins.AutoSave} sender Plugin instance sending the event. * @param {Object} draft Draft object containing the HTML contents of the editor. */ self.onRestoreDraft = new Dispatcher(self); /** * This event gets fired when a draft removed/expired. * * @event onRemoveDraft * @param {tinymce.plugins.AutoSave} sender Plugin instance sending the event. * @param {Object} draft Draft object containing the HTML contents of the editor. */ self.onRemoveDraft = new Dispatcher(self); // Add ask before unload dialog only add one unload handler if (!unloadHandlerAdded) { window.onbeforeunload = tinymce.plugins.AutoSave._beforeUnloadHandler; unloadHandlerAdded = TRUE; } }, /** * Returns information about the plugin as a name/value array. * The current keys are longname, author, authorurl, infourl and version. * * @method getInfo * @return {Object} Name/value array containing information about the plugin. */ getInfo : function() { return { longname : 'Auto save', author : 'Moxiecode Systems AB', authorurl : 'http://tinymce.moxiecode.com', infourl : 'http://wiki.moxiecode.com/index.php/TinyMCE:Plugins/autosave', version : tinymce.majorVersion + "." + tinymce.minorVersion }; }, /** * Returns an expiration date UTC string. * * @method getExpDate * @return {String} Expiration date UTC string. */ getExpDate : function() { return new Date( new Date().getTime() + this.editor.settings.autosave_retention ).toUTCString(); }, /** * This method will setup the storage engine. If the browser has support for it. * * @method setupStorage */ setupStorage : function(ed) { var self = this, testKey = PLUGIN_NAME + '_test', testVal = "OK"; self.key = PLUGIN_NAME + ed.id; // Loop though each storage engine type until we find one that works tinymce.each([ function() { // Try HTML5 Local Storage if (localStorage) { localStorage.setItem(testKey, testVal); if (localStorage.getItem(testKey) === testVal) { localStorage.removeItem(testKey); return localStorage; } } }, function() { // Try HTML5 Session Storage if (sessionStorage) { sessionStorage.setItem(testKey, testVal); if (sessionStorage.getItem(testKey) === testVal) { sessionStorage.removeItem(testKey); return sessionStorage; } } }, function() { // Try IE userData if (tinymce.isIE) { ed.getElement().style.behavior = "url('#default#userData')"; // Fake localStorage on old IE return { autoExpires : TRUE, setItem : function(key, value) { var userDataElement = ed.getElement(); userDataElement.setAttribute(key, value); userDataElement.expires = self.getExpDate(); userDataElement.save("TinyMCE"); }, getItem : function(key) { var userDataElement = ed.getElement(); userDataElement.load("TinyMCE"); return userDataElement.getAttribute(key); }, removeItem : function(key) { ed.getElement().removeAttribute(key); } }; } }, ], function(setup) { // Try executing each function to find a suitable storage engine try { self.storage = setup(); if (self.storage) return false; } catch (e) { // Ignore } }); }, /** * This method will store the current contents in the the storage engine. * * @method storeDraft */ storeDraft : function() { var self = this, storage = self.storage, editor = self.editor, expires, content; // Is the contents dirty if (storage) { // If there is no existing key and the contents hasn't been changed since // it's original value then there is no point in saving a draft if (!storage.getItem(self.key) && !editor.isDirty()) return; // Store contents if the contents if longer than the minlength of characters content = editor.getContent(); if (content.length > editor.settings.autosave_minlength) { expires = self.getExpDate(); // Store expiration date if needed IE userData has auto expire built in if (!self.storage.autoExpires) self.storage.setItem(self.key + "_expires", expires); self.storage.setItem(self.key, content); self.onStoreDraft.dispatch(self, { expires : expires, content : content }); } } }, /** * This method will restore the contents from the storage engine back to the editor. * * @method restoreDraft */ restoreDraft : function() { var self = this, storage = self.storage; if (storage) { content = storage.getItem(self.key); if (content) { self.editor.setContent(content); self.onRestoreDraft.dispatch(self, { content : content }); } } }, /** * This method will return true/false if there is a local storage draft available. * * @method hasDraft * @return {boolean} true/false state if there is a local draft. */ hasDraft : function() { var self = this, storage = self.storage, expDate, exists; if (storage) { // Does the item exist at all exists = !!storage.getItem(self.key); if (exists) { // Storage needs autoexpire if (!self.storage.autoExpires) { expDate = new Date(storage.getItem(self.key + "_expires")); // Contents hasn't expired if (new Date().getTime() < expDate.getTime()) return TRUE; // Remove it if it has self.removeDraft(); } else return TRUE; } } return false; }, /** * Removes the currently stored draft. * * @method removeDraft */ removeDraft : function() { var self = this, storage = self.storage, key = self.key, content; if (storage) { // Get current contents and remove the existing draft content = storage.getItem(key); storage.removeItem(key); storage.removeItem(key + "_expires"); // Dispatch remove event if we had any contents if (content) { self.onRemoveDraft.dispatch(self, { content : content }); } } }, "static" : { // Internal unload handler will be called before the page is unloaded _beforeUnloadHandler : function(e) { var msg; tinymce.each(tinyMCE.editors, function(ed) { // Store a draft for each editor instance if (ed.plugins.autosave) ed.plugins.autosave.storeDraft(); // Never ask in fullscreen mode if (ed.getParam("fullscreen_is_enabled")) return; // Setup a return message if the editor is dirty if (!msg && ed.isDirty() && ed.getParam("autosave_ask_before_unload")) msg = ed.getLang("autosave.unload_msg"); }); return msg; } } }); tinymce.PluginManager.add('autosave', tinymce.plugins.AutoSave); })(tinymce);
JavaScript