code stringlengths 1 2.08M | language stringclasses 1
value |
|---|---|
/**
* 입력된 내용을 배열에 저장 후 정렬
*/
function arrayTestInit() {
array=new Array();
cnt = 0;
document.getElementById('btnAdd').onclick = addFunc;
document.getElementById('btnView').onclick = viewFunc;
document.getElementById('btnSort').onclick = sortFunc;
document.getElementById('btnNumSort').onclick = numSortFunc;
}
function addFunc(){
var f = document.frm;
var d = f.data.value;
array[cnt]=d;
cnt++;
}
function viewFunc(){
var f=document.frm;
var rst=document.getElementById('resultDiv');
f.result.value=array.join('\n');
rst.innerHTML=array.join('<br/>');
}
function sortFunc(){
var f=document.frm;
var rst=document.getElementById('resultDiv');
array.sort();
f.result.value=array.join('\n');
rst.innerHTML=array.join('<br/>');
}
function numSortFunc()
{
var f=document.frm;
var rst=document.getElementById('resultDiv');
array.sort(numSort);//numSort를 부르는데 매개변수를 안보내지만 받는다..
f.result.value=array.join('\n');
rst.innerHTML=array.join('<br/>');
}
function numSort(x,y)
{
//return Number(x)-Number(y);//오름차순
return Number(y)-Number(x);//내임차순!
}
| JavaScript |
/**
*
*/ | JavaScript |
/**
*
*/
function win_openinit()
{
document.getElementById('btnfind').onclick=btnc;
win=win.open('http://www,naver.com','win','');
}
function winSubInit()
{
tar=window.opener.document.frm;
tar.address.value='우편번호를 검색하세요';
var s=document.getElementById('sel');
s.onchange=function()
{
var pos = s.selectedIndex;
var zip = s[pos].value.split('-');
var address = s[pos].text;
tar.zip1.value=zip[0];
tar.zip1.value=zip[1];
tar.address.value=address;
}
} | JavaScript |
/**
*
*/
var interval;
var cnt=0;
var week=['일','월','화','수','목','금','토'];
function intervalinit()
{
document.getElementById('btnstart').onclick=stafunc;
document.getElementById('btnstop').onclick=stofunc;
}
function stafunc()
{
interval=setInterval(clock, 1000);
}
function stofunc()
{
clearInterval(interval);
}
function clock()
{
var now=new Date();
cnt=now.getFullYear()+'년';
cnt+=(now.getMonth()+1)+'월';
cnt+=(now.getDate())+'일(';
cnt+=week[now.getDate()]+'요일)';
cnt+=now.getHours()+':';
cnt+=now.getMinutes()+':';
cnt+=now.getSeconds();
var r = document.getElementById('result');
r.innerHTML = cnt;
}
| JavaScript |
/**
*
*/
var start=false;
var startx=0,starty=0;
var ctx;
function deawinginit()
{
document.getElementById('canvas').onmousemove=chk;
document.getElementById('canvas').onmouseup=set;
ctx=document.getElementById('canvas').getContext('2d');
}
function set(ev)
{
var lc;
var lw;
start=!start;
startx=ev.x;
starty=ev.y;
//선그리기
if(start)
{
ctx.beginPath();
ctx.moveTo(startx, starty);
lc=document.getElementById('lineColor');
lw=document.getElementById('lineWidth');
ctx.strokeStyle=lc.value;
ctx.lineWidth=lw.value;
}
else
{
ctx.closePath();
}
}
function chk(ev)
{
var d = document.getElementById('result');
var x=ev.x;
var y=ev.y;
d.innerHTML='x='+x+', y='+y;
if(start)
{
ctx.lineTo(x,y);
ctx.stroke();
}
}
| JavaScript |
/**
* 자바스크립트 외부파일정의 테스트
* 작성일 : 20141029
* 작성자 : 궈니켜니
*/
window.onload=function()
{
//but2 버튼이 클릭되면
var b2 = document.getElementById('btn2');
b2.onclick=function()
{
var rBar=document.getElementById('ran');
alert(rBar.value);
}
var b = document.getElementById("btn");
b.onclick=function()
{
var s1 = document.getElementById("su1");
var s2 = document.getElementById("su2");
var r = Number(s1.value)+Number(s2.value);
alert(r);
}
} | JavaScript |
/**
*if문 테스트
*/
function iftest()
{
/*btn 버튼에 클릭되면*/
var b = document.getElementById('btn')
var f;
b.onclick=function()
{
f=document.frm;
var n=f.irum.value;
var s=Number(f.score.value);
if(s>=50)
{
alert(n+"합격");
}
else
{
alert(n+"불합격");
}
}
} | JavaScript |
/**
*
*/
function radioinit()
{
document.getElementById('btn').onclick=cfunc;
var f = document.frm;
var l = f.rb.length;
for(i=0;i<l;i++)
{
f.rb[i].onclick=cfunc;
}
}
function cfunc()
{
var f = document.frm;
var l = f.rb.length;
for(i=0;i<l;i++){
if(f.rb[i].checked)
{
var array=f.rb[i].value.split(',');
f.re.style.backgroundColor=array[0];
f.re.style.color=array[1];
f.re.value='빽그라운드'+array[0]+'\n글씨색'+array[1];
}
}
} | JavaScript |
/**
* 로그인/아웃 처리
*/
function titleinit()
{
var btnlogin;
var btnlogout;
btnlogin=document.getElementById('btnlogin');
btnlogout=document.getElementById('btnlogout');
if(btnlogin != null)
{
btnlogin.onclick=function()
{
var f = document.frm;
if(f.mid.value==''||f.pwd.value=='')
{
alert('id와 암호 확인바람');
}
else
{
f.submit();
//location.href='../member/login.jsp';
}
}
}
if(btnlogout != null)
{
btnlogout.onclick=function()
{
location.href='../member/logout.jsp';
}
}
} | JavaScript |
/**
* 게시판과 관련된 자바스크립트
* date : 2014,11,3
* author : kyun
*/
function general()//게시판에서 사용하는 공통모듈
{
if(document.getElementById('btnlist')!=null)
{
document.getElementById('btnlist').onclick=function()
{
location.href='list.jsp';
}
}
if(document.getElementById('btninput')!=null)
{
document.getElementById('btninput').onclick=function()
{
location.href='input.jsp';
}
}
if(document.getElementById('btnmodify')!=null)
{
document.getElementById('btnmodify').onclick=function()
{
location.href='modify.jsp';
}
}
if(document.getElementById('btndelete')!=null)
{
document.getElementById('btndelete').onclick=function()
{
location.href='delete_result.jsp';
}
}
if(document.getElementById('btnview')!=null)
{
document.getElementById('btnview').onclick=function()
{
location.href='view.jsp';
}
}
if(document.getElementById('btnsave')!=null)
{
document.getElementById('btnsave').onclick=function()
{
location.href='input_result.jsp';
}
}
}
function goPage(page)
{
location.href='view.jsp?page='+page;//getter와 같은뜻
}
function inputinit()//input과 관련된 모듈
{
general();
}
function listinit()
{
general();
}
function viewinit()
{
general();
}
function modifyinit()
{
general();
}
function delete_resultinit()
{
general();
}
| JavaScript |
/**
*
*/
function forTestInit() {
var b = document.getElementById('btn');
b.onclick = btnFunc;
}
function btnFunc() {
var rst = document.getElementById('resultDiv');
var f = document.frm;
var s1 = Number(f.su1.value);
var s2 = Number(f.su2.value);
/*var temp = 0;*/
f.result.value = '';
rst.innerHTML = '';
/*swapping로직
*if(s1>s2){
*temp = s1;
*s1 = s2;
*s2 = temp;
*}
*for(a=s1; a<=s2; a++){
*if(a%3==0 || a%4==0)
*f.result.value += a+' ';
*rst.innerHTML += a+' ';}
*/
if(s1<s2){
for(a = s1; a <= s2; a++){
if(a%3==0 || a%4==0) {
f.result.value += a+' ';
rst.innerHTML += a+' ';
}
}
}else if(s1 > s2){
for(a=s2; a<=s1; a++){
if(a%3==0 || a%4==0){
f.result.value += a+' ';
rst.innerHTML += a+' ';
}
}
}
} | JavaScript |
/**
* 3의배수 출력
*/
function tryinit()
{
var f = document.frm;
document.getElementById('btnrun').onclick=function()
{
if(f.su1.value=='')
{
alert('첫번째빔');
f.su1.focus();
}
else if(f.su2.value=='')
{
alert('두번째빔');
f.su2.focus();
}
else
{
f.submit();
}
}
} | JavaScript |
/**
*게시판과 관련된 자바스크립트
*날짜 : 2014.11
*이름 : 안종휘
*/
var btnList, btnInput, btnModify, btnDelete, btnView;
var url="index.jsp?inc=./score/";
function general(){//게시판에서 사용하는 공통 모듈
btnList=document.getElementById('btnList');
if(btnList !=null){
btnList.onclick=function(){
var frm=document.hiddenFrm;
frm.action=url+"list.jsp";
alert(frm.action);
frm.submit();
//location.href=url+'list.jsp';
}
}
btnInput=document.getElementById('btnInput');
if(btnInput !=null){
btnInput.onclick=function(){
//location.href=url+'input.jsp';
var frm=document.hiddenFrm;
frm.action=url+"input.jsp";
frm.submit();
}
}
btnModify=document.getElementById('btnModify');
if(btnModify !=null){
btnModify.onclick=function(){
location.href=url+'modify.jsp';
}
}
btnDelete=document.getElementById('btnDelete');
if(btnDelete !=null){
btnDelete.onclick=function(){
var b= confirm("정말 삭제하시겠습니까?");
if(b){
var rno=document.hiddenFrm.rno.value;
location.href=url+'delete_result.jsp?rno='+rno;
}else{
alert("삭제작업이 취소되었습니다.");
}
}
}
btnView=document.getElementById('btnView');
if(btnView !=null){
btnView.onclick=function(){
location.href=url+'view.jsp';
}
}
}
function goPage(page){
//location.href=url+"view.jsp?page="+page;
var hf=document.hiddenFrm;
hf.nowPage.value = page;
hf.find.value=document.score_list_frm.find.value;
hf.action="index.jsp?inc=./score/list.jsp";
hf.submit();
}
function goView(page, rno){
var hf=document.hiddenFrm;
hf.nowPage.value = page;
hf.rno.value=rno;
hf.find.value=document.score_list_frm.find.value;
hf.action="index.jsp?inc=./score/view.jsp";
hf.submit();
}
function inputInit(){//input과 관련된 모듈
general();
}
function listInit(){
general();
goPage(page);
}
function viewInit(){
general();
}
function modifyInit(){
general();
}
function deleteInit(){
general();
} | JavaScript |
/**
*게시판과 관련된 자바스크립트
*날짜 : 2014.11
*이름 : 안종휘
*/
var btnList, btnInput, btnModify, btnDelete, btnView;
var url="index.jsp?inc=./member/";
function general(){//게시판에서 사용하는 공통 모듈
btnList=document.getElementById('btnList');
if(btnList !=null){
btnList.onclick=function(){
var frm=document.hiddenFrm;
frm.action=url+"list.jsp";
alert(frm.action);
frm.submit();
//location.href=url+'list.jsp';
}
}
btnInput=document.getElementById('btnInput');
if(btnInput !=null){
btnInput.onclick=function(){
//location.href=url+'input.jsp';
var frm=document.hiddenFrm;
frm.action=url+"input.jsp";
frm.submit();
}
}
btnModify=document.getElementById('btnModify');
if(btnModify !=null){
btnModify.onclick=function(){
location.href=url+'modify.jsp';
}
}
btnDelete=document.getElementById('btnDelete');
if(btnDelete !=null){
btnDelete.onclick=function(){
var b= confirm("정말 삭제하시겠습니까?");
if(b){
var f= document.memberFrm
f.action=url+'delete_result.jsp?rno='+rno;
f.submit();
}else{
alert("삭제작업이 취소되었습니다.");
}
}
}
btnView=document.getElementById('btnView');
if(btnView !=null){
btnView.onclick=function(){
location.href=url+'view.jsp';
}
}
}
function goPage(page){
//location.href=url+"view.jsp?page="+page;
var hf=document.hiddenFrm;
hf.nowPage.value = page;
hf.find.value=document.member_list_frm.find.value;
hf.action="index.jsp?inc=./member/list.jsp";
hf.submit();
}
function goView(page, rno){
var hf=document.hiddenFrm;
hf.nowPage.value = page;
hf.rno.value=rno;
hf.find.value=document.member_list_frm.find.value;
hf.action="index.jsp?inc=./member/view.jsp";
hf.submit();
}
function inputInit(){//input과 관련된 모듈
general();
}
function listInit(){
general();
goPage(page);
}
function viewInit(){
general();
}
function modifyInit(){
general();
}
function deleteInit(){
general();
} | JavaScript |
/**
*게시판과 관련된 자바스크립트
*날짜 : 2014.11
*이름 : 안종휘
*/
function general(){//게시판에서 사용하는 공통 모듈
if(document.getElementById('btnList') !=null){
document.getElementById('btnList').onclick=function(){
location.href='list.jsp';
}
}
if(document.getElementById('btnInput') !=null){
document.getElementById('btnInput').onclick=function(){
location.href='input.jsp';
}
}
if(document.getElementById('btnModify') !=null){
document.getElementById('btnModify').onclick=function(){
location.href='modify.jsp';
}
}
if(document.getElementById('btnDelete') !=null){
document.getElementById('btnDelete').onclick=function(){
location.href='delete_result.jsp';
}
}
if(document.getElementById('btnView') !=null){
document.getElementById('btnView').onclick=function(){
location.href='view.jsp';
}
}
}
function goPage(page){
location.href="view.jsp?page="+page;
}
function inputInit(){//input과 관련된 모듈
general();
}
function listInit(){
general();
}
function viewInit(){
general();
}
function modifyInit(){
general();
}
function deleteInit(){
general();
} | JavaScript |
// Copyright (c) 2012 eagleonhill(qiuc12@gmail.com). All rights reserved.
// Use of this source code is governed by a Mozilla-1.1 license that can be
// found in the LICENSE file.
replaceSubElements(document);
pageDOMLoaded = true;
if (needNotifyBar) {
showNotifyBar();
}
| JavaScript |
// Copyright (c) 2012 eagleonhill(qiuc12@gmail.com). All rights reserved.
// Use of this source code is governed by a Mozilla-1.1 license that can be
// found in the LICENSE file.
var tabStatus = {};
var version;
var firstRun = false;
var firstUpgrade = false;
var blackList = [
/^https?:\/\/[^\/]*\.taobao\.com\/.*/i,
/^https?:\/\/[^\/]*\.alipay\.com\/.*/i
];
var MAX_LOG = 400;
(function getVersion() {
$.ajax('manifest.json', {
success: function(v) {
v = JSON.parse(v);
version = v.version;
trackVersion(version);
}
});
})();
function startListener() {
chrome.extension.onConnect.addListener(function(port) {
if (!port.sender.tab) {
console.error('Not connect from tab');
return;
}
initPort(port);
});
chrome.extension.onRequest.addListener(
function(request, sender, sendResponse) {
if (!sender.tab) {
console.error('Request from non-tab');
} else if (request.command == 'Configuration') {
var config = setting.getPageConfig(request.href);
sendResponse(config);
if (request.top) {
resetTabStatus(sender.tab.id);
var dummy = {href: request.href, clsid: 'NULL', urldetect: true};
if (!config.pageRule &&
setting.getFirstMatchedRule(
dummy, setting.defaultRules)) {
detectControl(dummy, sender.tab.id, 0);
}
}
} else if (request.command == 'GetNotification') {
getNotification(request, sender, sendResponse);
} else if (request.command == 'DismissNotification') {
chrome.tabs.sendRequest(
sender.tab.id, {command: 'DismissNotificationPage'});
sendResponse({});
} else if (request.command == 'BlockSite') {
setting.blocked.push({type: 'wild', value: request.site});
setting.update();
sendResponse({});
}
}
);
}
var blocked = {};
function notifyUser(request, tabId) {
var s = tabStatus[tabId];
if (s.notify && (s.urldetect || s.count > s.actived)) {
console.log('Notify the user on tab ', tabId);
chrome.tabs.sendRequest(tabId, {command: 'NotifyUser', tabid: tabId}, null);
}
}
var greenIcon = chrome.extension.getURL('icon16.png');
var grayIcon = chrome.extension.getURL('icon16-gray.png');
var errorIcon = chrome.extension.getURL('icon16-error.png');
var responseCommands = {};
function resetTabStatus(tabId) {
tabStatus[tabId] = {
count: 0,
actived: 0,
error: 0,
urldetect: 0,
notify: true,
issueId: null,
logs: {'0': []},
objs: {'0': []},
frames: 1,
tracking: false
};
}
function initPort(port) {
var tabId = port.sender.tab.id;
if (!(tabId in tabStatus)) {
resetTabStatus(tabId);
}
var status = tabStatus[tabId];
var frameId = tabStatus[tabId].frames++;
status.logs[frameId] = [];
status.objs[frameId] = [];
port.onMessage.addListener(function(request) {
var resp = responseCommands[request.command];
if (resp) {
delete request.command;
resp(request, tabId, frameId);
} else {
console.error('Unknown command ' + request.command);
}
});
port.onDisconnect.addListener(function() {
for (var i = 0; i < status.objs[frameId].length; ++i) {
countTabObject(status, status.objs[frameId][i], -1);
}
showTabStatus(tabId);
if (status.tracking) {
if (status.count == 0) {
// Open the log page.
window.open('log.html?tabid=' + tabId);
status.tracking = false;
}
} else {
// Clean up after 1 min.
window.setTimeout(function() {
status.logs[frameId] = [];
status.objs[frameId] = [];
}, 60 * 1000);
}
});
}
chrome.tabs.onRemoved.addListener(function(tabId, removeInfo) {
if (tabStatus[tabId]) {
tabStatus[tabId].removed = true;
var TIMEOUT = 1000 * 60 * 5;
// clean up after 5 mins.
window.setTimeout(function() {
delete tabStatus[tabId];
}, TIMEOUT);
}
});
function countTabObject(status, info, delta) {
for (var i = 0; i < blackList.length; ++i) {
if (info.href.match(blackList[i])) {
return;
}
}
if (setting.getFirstMatchedRule(info, setting.blocked)) {
status.notify = false;
}
if (info.urldetect) {
status.urldetect += delta;
// That's not a object.
return;
}
if (info.actived) {
status.actived += delta;
if (delta > 0) {
trackUse(info.rule);
}
} else if (delta > 0) {
trackNotUse(info.href);
}
status.count += delta;
var issue = setting.getMatchedIssue(info);
if (issue) {
status.error += delta;
status.issueId = issue.identifier;
if (delta > 0) {
trackIssue(issue);
}
}
}
function showTabStatus(tabId) {
if (tabStatus[tabId].removed) {
return;
}
var status = tabStatus[tabId];
var title = '';
var iconPath = greenIcon;
if (!status.count && !status.urldetect) {
chrome.pageAction.hide(tabId);
return;
} else {
chrome.pageAction.show(tabId);
}
if (status.urldetect) {
// Matched some rule.
iconPath = grayIcon;
title = $$('status_urldetect');
} else if (status.count == 0) {
// Do nothing..
} else if (status.error != 0) {
// Error
iconPath = errorIcon;
title = $$('status_error');
} else if (status.count != status.actived) {
// Disabled..
iconPath = grayIcon;
title = $$('status_disabled');
} else {
// OK
iconPath = greenIcon;
title = $$('status_ok');
}
chrome.pageAction.setIcon({
tabId: tabId,
path: iconPath
});
chrome.pageAction.setTitle({
tabId: tabId,
title: title
});
chrome.pageAction.setPopup({
tabId: tabId,
popup: 'popup.html?tabid=' + tabId
});
}
function detectControl(request, tabId, frameId) {
var status = tabStatus[tabId];
if (frameId != 0 && status.objs[0].length) {
// Remove the item to identify the page.
countTabObject(status, status.objs[0][0], -1);
status.objs[0] = [];
}
status.objs[frameId].push(request);
countTabObject(status, request, 1);
showTabStatus(tabId);
notifyUser(request, tabId);
}
responseCommands.DetectControl = detectControl;
responseCommands.Log = function(request, tabId, frameId) {
var logs = tabStatus[tabId].logs[frameId];
if (logs.length < MAX_LOG) {
logs.push(request.message);
} else if (logs.length == MAX_LOG) {
logs.push('More logs clipped');
}
};
function generateLogFile(tabId) {
var status = tabStatus[tabId];
if (!status) {
return 'No log for tab ' + tabId;
}
var ret = '---------- Start of log --------------\n';
ret += 'UserAgent: ' + navigator.userAgent + '\n';
ret += 'Extension version: ' + version + '\n';
ret += '\n';
var frameCount = 0;
for (var i = 0; i < status.frames; ++i) {
if (status.objs[i].length == 0 && status.logs[i].length == 0) {
continue;
}
if (frameCount) {
ret += '\n\n';
}
++frameCount;
ret += '------------ Frame ' + (i + 1) + ' ------------------\n';
ret += 'Objects:\n';
for (var j = 0; j < status.objs[i].length; ++j) {
ret += JSON.stringify(status.objs[i][j]) + '\n';
}
ret += '\n';
ret += 'Log:\n';
for (var j = 0; j < status.logs[i].length; ++j) {
ret += status.logs[i][j] + '\n';
}
}
ret += '\n---------------- End of log ---------------\n';
if (frameCount == 0) {
return 'No log for tab ' + tabId;
}
return ret;
}
function getNotification(request, sender, sendResponse) {
var tabid = sender.tab.id;
chrome.tabs.get(tabid, function(tab) {
var config = {};
config.tabId = tab.id;
config.site = tab.url.replace(/[^:]*:\/\/([^\/]*).*/, '$1');
config.sitePattern = tab.url.replace(/([^:]*:\/\/[^\/]*).*/, '$1/*');
if (tabStatus[tabid].urldetect) {
config.message = $$('status_urldetect');
} else {
config.message = $$('status_disabled');
}
config.closeMsg = $$('bar_close');
config.enableMsg = $$('bar_enable');
config.blockMsg = $$('bar_block', config.site);
sendResponse(config);
});
}
| JavaScript |
// Copyright (c) 2012 eagleonhill(qiuc12@gmail.com). All rights reserved.
// Use of this source code is governed by a Mozilla-1.1 license that can be
// found in the LICENSE file.
/*
Rule: {
identifier: an unique identifier
title: description
type: Can be "wild", "regex", "clsid"
value: pattern, correspond to type
userAgent: the useragent value. See var "agents" for options.
script: script to inject. Separated by spaces
}
Order: {
status: enabled / disabled / custom
position: default / custom
identifier: identifier of rule
}
Issue: {
type: Can be "wild", "regex", "clsid"
value: pattern, correspond to type
description: The description of this issue
issueId: Issue ID on issue tracking page
url: optional, support page for issue tracking.
Use code.google.com if omitted.
}
ServerSide:
ActiveXConfig: {
version: version
rules: object of user-defined rules, propertied by identifiers
defaultRules: ojbect of default rules
scripts: mapping of workaround scripts, by identifiers.
order: the order of rules
cache: to accerlerate processing
issues: The bugs/unsuppoted sites that we have accepted.
misc:{
lastUpdate: last timestamp of updating
logEnabled: log
tracking: Allow GaS tracking.
verbose: verbose level of logging
}
}
PageSide:
ActiveXConfig: {
pageSide: Flag of pageSide.
pageScript: Helper script to execute on context of page
extScript: Helper script to execute on context of extension
pageRule: If page is matched.
clsidRules: If page is not matched or disabled. valid CLSID rules
logEnabled: log
verbose: verbose level of logging
}
*/
function ActiveXConfig(input)
{
var settings;
if (input === undefined) {
var defaultSetting = {
version: 3,
rules: {},
defaultRules: {},
scriptContents: {},
scripts: {},
order: [],
notify: [],
issues: [],
blocked: [],
misc: {
lastUpdate: 0,
logEnabled: false,
tracking: true,
verbose: 3
}
};
input = defaultSetting;
}
settings = ActiveXConfig.convertVersion(input);
settings.removeInvalidItems();
settings.update();
return settings;
}
var settingKey = 'setting';
clsidPattern = /[^0-9A-F][0-9A-F]{8}-([0-9A-F]{4}-){3}[0-9A-F]{12}[^0-9A-F]/;
var agents = {
ie9: 'Mozilla/5.0 (compatible; MSIE 9.0; Windows NT 6.1; WOW64; Trident/5.0)',
ie8: 'Mozilla/4.0 (compatible; MSIE 8.0; Windows NT 6.0; WOW64; Trident/4.0)',
ie7: 'Mozilla/4.0 (compatible; MSIE 7.0; Windows NT 6.0; WOW64;)',
ff7win: 'Mozilla/5.0 (Windows NT 6.1; WOW64; rv:7.0.1)' +
' Gecko/20100101 Firefox/7.0.1',
ip5: 'Mozilla/5.0 (iPhone; CPU iPhone OS 5_0 like Mac OS X)' +
' AppleWebKit/534.46 (KHTML, like Gecko) Version/5.1' +
' Mobile/9A334 Safari/7534.48.3',
ipad5: 'Mozilla/5.0 (iPad; CPU OS 5_0 like Mac OS X) AppleWebKit/534.46' +
'(KHTML, like Gecko) Version/5.1 Mobile/9A334 Safari/7534.48.3'
};
function getUserAgent(key) {
// This script is always run under sandbox, so useragent should be always
// correct.
if (!key || !(key in agents)) {
return '';
}
var current = navigator.userAgent;
var wow64 = current.indexOf('WOW64') >= 0;
var value = agents[key];
if (!wow64) {
value = value.replace(' WOW64;', '');
}
return value;
}
ActiveXConfig.convertVersion = function(setting) {
if (setting.version == 3) {
if (!setting.blocked) {
setting.blocked = [];
}
setting.__proto__ = ActiveXConfig.prototype;
return setting;
} else if (setting.version == 2) {
function parsePattern(pattern) {
pattern = pattern.trim();
var title = pattern.match(/###(.*)/);
if (title) {
return {
pattern: pattern.match(/(.*)###/)[1].trim(),
title: title[1].trim()
};
} else {
return {
pattern: pattern,
title: 'Rule'
};
}
}
var ret = new ActiveXConfig();
if (setting.logEnabled) {
ret.misc.logEnabled = true;
}
var urls = setting.url_plain.split('\n');
for (var i = 0; i < urls.length; ++i) {
var rule = ret.createRule();
var pattern = parsePattern(urls[i]);
rule.title = pattern.title;
var url = pattern.pattern;
if (url.substr(0, 2) == 'r/') {
rule.type = 'regex';
rule.value = url.substr(2);
} else {
rule.type = 'wild';
rule.value = url;
}
ret.addCustomRule(rule, 'convert');
}
var clsids = setting.trust_clsids.split('\n');
for (var i = 0; i < clsids.length; ++i) {
var rule = ret.createRule();
rule.type = 'clsid';
var pattern = parsePattern(clsids[i]);
rule.title = pattern.title;
rule.value = pattern.pattern;
ret.addCustomRule(rule, 'convert');
}
firstUpgrade = true;
return ret;
}
};
ActiveXConfig.prototype = {
// Only used for user-scripts
shouldEnable: function(object) {
if (this.pageRule) {
return this.pageRule;
}
var clsidRule = this.getFirstMatchedRule(object, this.clsidRules);
if (clsidRule) {
return clsidRule;
} else {
return null;
}
},
createRule: function() {
return {
title: 'Rule',
type: 'wild',
value: '',
userAgent: '',
scriptItems: ''
};
},
removeInvalidItems: function() {
if (this.pageSide) {
return;
}
function checkIdentifierMatches(item, prop) {
if (typeof item[prop] != 'object') {
console.log('reset ', prop);
item[prop] = {};
}
for (var i in item[prop]) {
var ok = true;
if (typeof item[prop][i] != 'object') {
ok = false;
}
if (ok && item[prop][i].identifier != i) {
ok = false;
}
if (!ok) {
console.log('remove corrupted item ', i, ' in ', prop);
delete item[prop][i];
}
}
}
checkIdentifierMatches(this, 'rules');
checkIdentifierMatches(this, 'defaultRules');
checkIdentifierMatches(this, 'scripts');
checkIdentifierMatches(this, 'issues');
var newOrder = [];
for (var i = 0; i < this.order.length; ++i) {
if (this.getItem(this.order[i])) {
newOrder.push(this.order[i]);
} else {
console.log('remove order item ', this.order[i]);
}
}
this.order = newOrder;
},
addCustomRule: function(newItem, auto) {
if (!this.validateRule(newItem)) {
return;
}
var identifier = this.createIdentifier();
newItem.identifier = identifier;
this.rules[identifier] = newItem;
this.order.push({
status: 'custom',
position: 'custom',
identifier: identifier
});
this.update();
trackAddCustomRule(newItem, auto);
},
updateDefaultRules: function(newRules) {
var deleteAll = false, ruleToDelete = {};
if (typeof this.defaultRules != 'object') {
// There might be some errors!
// Clear all defaultRules
console.log('Corrupted default rules, reload all');
deleteAll = true;
this.defaultRules = {};
} else {
for (var i in this.defaultRules) {
if (!(i in newRules)) {
console.log('Remove rule ' + i);
ruleToDelete[i] = true;
delete this.defaultRules[i];
}
}
}
var newOrder = [];
for (var i = 0; i < this.order.length; ++i) {
if (this.order[i].position == 'custom' ||
(!deleteAll && !ruleToDelete[this.order[i].identifier])) {
newOrder.push(this.order[i]);
}
}
this.order = newOrder;
var position = 0;
for (var i in newRules) {
if (!(i in this.defaultRules)) {
this.addDefaultRule(newRules[i], position);
position++;
}
this.defaultRules[i] = newRules[i];
}
},
loadDefaultConfig: function() {
var setting = this;
$.ajax({
url: '/settings/setting.json',
dataType: 'json',
success: function(nv, status, xhr) {
console.log('Update default rules');
setting.updateDefaultRules(nv);
setting.update();
}
});
$.ajax({
url: '/settings/scripts.json',
dataType: 'json',
success: function(nv, status, xhr) {
console.log('Update scripts');
setting.scripts = nv;
setting.loadAllScripts();
setting.update();
}
});
$.ajax({
url: '/settings/issues.json',
dataType: 'json',
success: function(nv, status, xhr) {
setting.issues = nv;
setting.update();
}
});
},
getPageConfig: function(href) {
var ret = {};
ret.pageSide = true;
ret.version = this.version;
ret.verbose = this.misc.verbose;
ret.logEnabled = this.misc.logEnabled;
ret.pageRule = this.getFirstMatchedRule({href: href});
if (!ret.pageRule) {
ret.clsidRules = this.cache.clsidRules;
} else {
var script = this.getScripts(ret.pageRule.script);
ret.pageScript = script.page;
ret.extScript = script.extension;
}
return ret;
},
getFirstMatchedRule: function(object, rules) {
var useCache = false;
if (!rules) {
rules = this.cache.validRules;
useCache = true;
}
if (Array.isArray(rules)) {
for (var i = 0; i < rules.length; ++i) {
if (this.isRuleMatched(rules[i], object, useCache ? i : -1)) {
return rules[i];
}
}
} else {
for (var i in rules) {
if (this.isRuleMatched(rules[i], object)) {
return rules[i];
}
}
}
return null;
},
getMatchedIssue: function(filter) {
return this.getFirstMatchedRule(filter, this.issues);
},
activeRule: function(rule) {
for (var i = 0; i < this.order.length; ++i) {
if (this.order[i].identifier == rule.identifier) {
if (this.order[i].status == 'disabled') {
this.order[i].status = 'enabled';
trackAutoEnable(rule.identifier);
}
break;
}
}
this.update();
},
validateRule: function(rule) {
var ret = true;
try {
if (rule.type == 'wild') {
ret &= this.convertUrlWildCharToRegex(rule.value) != null;
} else if (rule.type == 'regex') {
ret &= rule.value != '';
var r = new RegExp(rule.value, 'i');
} else if (rule.type == 'clsid') {
var v = rule.value.toUpperCase();
if (!clsidPattern.test(v) || v.length > 55)
ret = false;
}
} catch (e) {
ret = false;
}
return ret;
},
isRuleMatched: function(rule, object, id) {
if (rule.type == 'wild' || rule.type == 'regex') {
var regex;
if (id >= 0) {
regex = this.cache.regex[id];
} else if (rule.type == 'wild') {
regex = this.convertUrlWildCharToRegex(rule.value);
} else if (rule.type == 'regex') {
regex = new RegExp('^' + rule.value + '$', 'i');
}
if (object.href && regex.test(object.href)) {
return true;
}
} else if (rule.type == 'clsid') {
if (object.clsid) {
var v1 = clsidPattern.exec(rule.value.toUpperCase());
var v2 = clsidPattern.exec(object.clsid.toUpperCase());
if (v1 && v2 && v1[0] == v2[0]) {
return true;
}
}
}
return false;
},
getScripts: function(script) {
var ret = {
page: '',
extension: ''
};
if (!script) {
return ret;
}
var items = script.split(' ');
for (var i = 0; i < items.length; ++i) {
if (!items[i] || !this.scripts[items[i]]) {
continue;
}
var name = items[i];
var val = '// ';
val += items[i] + '\n';
val += this.scriptsContents[name];
val += '\n\n';
ret[this.scripts[name].context] += val;
}
return ret;
},
convertUrlWildCharToRegex: function(wild) {
try {
function escapeRegex(str, star) {
if (!star) star = '*';
var escapeChars = /([\.\\\/\?\{\}\+\[\]])/g;
return str.replace(escapeChars, '\\$1').replace('*', star);
}
wild = wild.toLowerCase();
if (wild == '<all_urls>') {
wild = '*://*/*';
}
var pattern = /^(.*?):\/\/(\*?[^\/\*]*)\/(.*)$/i;
// pattern: [all, scheme, host, page]
var parts = pattern.exec(wild);
if (parts == null) {
return null;
}
var scheme = parts[1];
var host = parts[2];
var page = parts[3];
var regex = '^' + escapeRegex(scheme, '[^:]*') + ':\\/\\/';
regex += escapeRegex(host, '[^\\/]*') + '/';
regex += escapeRegex(page, '.*');
return new RegExp(regex, 'i');
} catch (e) {
return null;
}
},
update: function() {
if (this.pageSide) {
return;
}
this.updateCache();
if (this.cache.listener) {
this.cache.listener.trigger('update');
}
this.save();
},
// Please remember to call update() after all works are done.
addDefaultRule: function(rule, position) {
console.log('Add new default rule: ', rule);
var custom = null;
if (rule.type == 'clsid') {
for (var i in this.rules) {
var info = {href: 'not-a-URL-/', clsid: rule.value};
if (this.isRuleMatched(this.rules[i], info, -1)) {
custom = this.rules[i];
break;
}
}
} else if (rule.keyword && rule.testUrl) {
// Try to find matching custom rule
for (var i in this.rules) {
if (this.isRuleMatched(this.rules[i], {href: rule.testUrl}, -1)) {
if (this.rules[i].value.toLowerCase().indexOf(rule.keyword) != -1) {
custom = this.rules[i];
break;
}
}
}
}
var newStatus = 'disabled';
if (custom) {
console.log('Convert custom rule', custom, ' to default', rule);
// Found a custom rule which is similiar to this default rule.
newStatus = 'enabled';
// Remove old one
delete this.rules[custom.identifier];
for (var i = 0; i < this.order.length; ++i) {
if (this.order[i].identifier == custom.identifier) {
this.order.splice(i, 1);
break;
}
}
}
this.order.splice(position, 0, {
position: 'default',
status: newStatus,
identifier: rule.identifier
});
this.defaultRules[rule.identifier] = rule;
},
updateCache: function() {
if (this.pageSide) {
return;
}
this.cache = {
validRules: [],
regex: [],
clsidRules: [],
userAgentRules: [],
listener: (this.cache || {}).listener
};
for (var i = 0; i < this.order.length; ++i) {
if (['custom', 'enabled'].indexOf(this.order[i].status) >= 0) {
var rule = this.getItem(this.order[i]);
var cacheId = this.cache.validRules.push(rule) - 1;
if (rule.type == 'clsid') {
this.cache.clsidRules.push(rule);
} else if (rule.type == 'wild') {
this.cache.regex[cacheId] =
this.convertUrlWildCharToRegex(rule.value);
} else if (rule.type == 'regex') {
this.cache.regex[cacheId] = new RegExp('^' + rule.value + '$', 'i');
}
if (rule.userAgent != '') {
this.cache.userAgentRules.push(rule);
}
}
}
},
save: function() {
if (location.protocol == 'chrome-extension:') {
// Don't include cache in localStorage.
var cache = this.cache;
delete this.cache;
var scripts = this.scriptsContents;
delete this.scriptsContents;
localStorage[settingKey] = JSON.stringify(this);
this.cache = cache;
this.scriptsContents = scripts;
}
},
createIdentifier: function() {
var base = 'custom_' + Date.now() + '_' + this.order.length + '_';
var ret;
do {
ret = base + Math.round(Math.random() * 65536);
} while (this.getItem(ret));
return ret;
},
getItem: function(item) {
var identifier = item;
if (typeof identifier != 'string') {
identifier = item.identifier;
}
if (identifier in this.rules) {
return this.rules[identifier];
} else {
return this.defaultRules[identifier];
}
},
loadAllScripts: function() {
this.scriptsContents = {};
setting = this;
for (var i in this.scripts) {
var item = this.scripts[i];
$.ajax({
url: '/settings/' + item.url,
datatype: 'text',
context: item,
success: function(nv, status, xhr) {
setting.scriptsContents[this.identifier] = nv;
}
});
}
}
};
function loadLocalSetting() {
var setting = undefined;
if (localStorage[settingKey]) {
try {
setting = JSON.parse(localStorage[settingKey]);
} catch (e) {
setting = undefined;
}
}
if (!setting) {
firstRun = true;
}
return new ActiveXConfig(setting);
}
function clearSetting() {
localStorage.removeItem(settingKey);
setting = loadLocalSetting();
}
| JavaScript |
// Copyright (c) 2012 eagleonhill(qiuc12@gmail.com). All rights reserved.
// Use of this source code is governed by a Mozilla-1.1 license that can be
// found in the LICENSE file.
var tabId = parseInt(location.href.replace(/.*tabid=([0-9]*).*/, '$1'));
if (isNaN(tabId)) {
alert('Invalid tab id');
}
var backgroundPage = chrome.extension.getBackgroundPage();
var tabInfo = backgroundPage.tabStatus[tabId];
var setting = backgroundPage.setting;
if (!tabInfo) {
alert('Cannot get tab tabInfo');
}
$(document).ready(function() {
$('.status').hide();
$('#submitissue').hide();
if (tabInfo.urldetect) {
$('#status_urldetect').show();
} else if (!tabInfo.count) {
// Shouldn't have this popup
} else if (tabInfo.error) {
$('#status_error').show();
} else if (tabInfo.count != tabInfo.actived) {
$('#status_disabled').show();
} else {
$('#status_ok').show();
$('#submitissue').show();
}
});
$(document).ready(function() {
$('#issue_view').hide();
if (tabInfo.error !== 0) {
var errorid = tabInfo.issueId;
var issue = setting.issues[errorid];
$('#issue_content').text(issue.description);
var url = issue.url;
if (!url) {
var issueUrl = 'http://code.google.com/p/np-activex/issues/detail?id=';
url = issueUrl + issue.issueId;
}
$('#issue_track').click(function() {
chrome.tabs.create({url: url});
window.close();
});
$('#issue_view').show();
}
});
function refresh() {
alert($$('refresh_needed'));
window.close();
}
function showEnableBtns() {
var list = $('#enable_btns');
list.hide();
if (tabInfo.urldetect || tabInfo.count > tabInfo.actived) {
list.show();
var info = {actived: true};
for (var i = 0; i < tabInfo.frames && info.actived; ++i) {
for (var j = 0; j < tabInfo.objs[i].length && info.actived; ++j) {
info = tabInfo.objs[i][j];
}
}
if (info.actived) {
return;
}
var rule = setting.getFirstMatchedRule(info, setting.defaultRules);
if (rule) {
var button = $('<button>').addClass('defaultRule');
button.text($$('enable_default_rule', rule.title));
button.click(function() {
setting.activeRule(rule);
refresh();
});
list.append(button);
} else {
var site = info.href.replace(/[^:]*:\/\/([^\/]*).*/, '$1');
var sitepattern = info.href.replace(/([^:]*:\/\/[^\/]*).*/, '$1/*');
var btn1 = $('<button>').addClass('customRule').
text($$('add_rule_site', site)).click(function() {
var rule = setting.createRule();
rule.type = 'wild';
rule.value = sitepattern;
setting.addCustomRule(rule, 'popup');
refresh();
});
var clsid = info.clsid;
var btn2 = $('<button>').addClass('customRule').
text($$('add_rule_clsid')).click(function() {
var rule = setting.createRule();
rule.type = 'clsid';
rule.value = clsid;
setting.addCustomRule(rule, 'popup');
refresh();
});
list.append(btn1).append(btn2);
}
}
}
$(document).ready(function() {
$('#submitissue').click(function() {
tabInfo.tracking = true;
alert($$('issue_submitting_desp'));
window.close();
});
});
$(document).ready(showEnableBtns);
| JavaScript |
var setting = loadLocalSetting();
var updateSession = new ObjectWithEvent();
setting.cache.listener = updateSession;
startListener();
registerRequestListener();
// If you want to build your own copy with a different id, please keep the
// tracking enabled.
var default_id = 'lgllffgicojgllpmdbemgglaponefajn';
var debug = chrome.i18n.getMessage('@@extension_id') != default_id;
if (debug && firstRun) {
if (confirm('Debugging mode. Disable tracking?')) {
setting.misc.tracking = false;
setting.misc.logEnabled = true;
}
}
setting.loadDefaultConfig();
chrome.runtime.onInstalled.addListener(function(details) {
var showwelcome = false;
if (details.reason == 'install') {
showwelcome = true;
}
if (showwelcome) {
open('welcome.html');
}
});
| JavaScript |
// Copyright (c) 2012 eagleonhill(qiuc12@gmail.com). All rights reserved.
// Use of this source code is governed by a Mozilla-1.1 license that can be
// found in the LICENSE file.
var controlLogFName = '__npactivex_log';
var controlLogEvent = '__npactivex_log_event__';
var config = null;
var port = null;
var logs = [];
var scriptConfig = {
none2block: false,
formid: false,
documentid: false,
activate_inplace: false
};
function onControlLog(event) {
var message = event.data;
log(message);
}
window.addEventListener(controlLogEvent, onControlLog, false);
function connect() {
if (port) {
return;
}
port = chrome.extension.connect();
for (var i = 0; i < logs.length; ++i) {
port.postMessage({command: 'Log', message: logs[i]});
}
if (port && config) {
logs = undefined;
}
}
function log(message) {
var time = (new Date()).toLocaleTimeString();
message = time + ' ' + message;
if (config && config.logEnabled) {
console.log(message);
}
if (port) {
port.postMessage({command: 'Log', message: message});
}
if (!config || !port) {
logs.push(message);
}
}
log('PageURL: ' + location.href);
var pendingObjects = [];
function init(response) {
config = new ActiveXConfig(response);
if (config.logEnabled) {
for (var i = 0; i < logs.length; ++i) {
console.log(logs[i]);
}
}
eval(config.extScript);
executeScript(config.pageScript);
setUserAgent();
log('Page rule:' + JSON.stringify(config.pageRule));
for (var i = 0; i < pendingObjects.length; ++i) {
pendingObjects[i].activex_process = false;
process(pendingObjects[i]);
cacheConfig();
}
delete pendingObjects;
}
function cacheConfig() {
sessionStorage.activex_config_cache = JSON.stringify(config);
}
function loadConfig(response) {
if (config) {
config = new ActiveXConfig(response);
var cache = sessionStorage.activex_config_cache;
if (cache) {
cacheConfig();
}
} else {
init(response);
}
if (config.pageRule) {
cacheConfig();
}
}
function loadSessionConfig() {
var cache = sessionStorage.activex_config_cache;
if (cache) {
log('Loading config from session cache');
init(JSON.parse(cache));
}
}
loadSessionConfig();
var notifyBar = null;
var pageDOMLoaded = false;
var needNotifyBar = false;
function showNotifyBar(request) {
if (notifyBar) {
return;
}
if (!pageDOMLoaded) {
needNotifyBar = true;
return;
}
notifyBar = {};
log('Create notification bar');
var barurl = chrome.extension.getURL('notifybar.html');
if (document.body.tagName == 'BODY') {
var iframe = document.createElement('iframe');
iframe.frameBorder = 0;
iframe.src = barurl;
iframe.height = '35px';
iframe.width = '100%';
iframe.style.top = '0px';
iframe.style.left = '0px';
iframe.style.zIndex = '2000';
iframe.style.position = 'fixed';
notifyBar.iframe = iframe;
document.body.insertBefore(iframe, document.body.firstChild);
var placeHolder = document.createElement('div');
placeHolder.style.height = iframe.height;
placeHolder.style.zIndex = '1999';
placeHolder.style.borderWidth = '0px';
placeHolder.style.borderStyle = 'solid';
placeHolder.style.borderBottomWidth = '1px';
document.body.insertBefore(placeHolder, document.body.firstChild);
notifyBar.placeHolder = placeHolder;
} else if (document.body.tagName == 'FRAMESET') {
// We can't do this..
return;
}
}
function dismissNotifyBar() {
if (!notifyBar || !notifyBar.iframe) {
return;
}
notifyBar.iframe.parentNode.removeChild(notifyBar.iframe);
notifyBar.placeHolder.parentNode.removeChild(notifyBar.placeHolder);
}
chrome.extension.onRequest.addListener(
function(request, sender, sendResponse) {
if (self == top && request.command == 'NotifyUser') {
showNotifyBar(request);
sendResponse({});
} else if (self == top && request.command == 'DismissNotificationPage') {
dismissNotifyBar();
sendResponse({});
}
});
chrome.extension.sendRequest(
{command: 'Configuration', href: location.href, top: self == top},
loadConfig);
window.addEventListener('beforeload', onBeforeLoading, true);
document.addEventListener('DOMSubtreeModified', onSubtreeModified, true);
| JavaScript |
// Copyright (c) 2010 eagleonhill(qiuc12@gmail.com). All rights reserved.
// Use of this source code is governed by a Mozilla-1.1 license that can be
// found in the LICENSE file.
var $$ = chrome.i18n.getMessage;
function loadI18n() {
var spans = document.querySelectorAll('[i18n]');
for (var i = 0; i < spans.length; ++i) {
var obj = spans[i];
v = $$(obj.getAttribute('i18n'));
if (v == '')
v = obj.getAttribute('i18n');
if (obj.tagName == 'INPUT') {
obj.value = v;
} else {
obj.innerText = v;
}
}
document.removeEventListener('DOMContentLoaded', loadI18n, false);
}
document.addEventListener('DOMContentLoaded', loadI18n, false);
| JavaScript |
// Copyright (c) 2012 eagleonhill(qiuc12@gmail.com). All rights reserved.
// Use of this source code is governed by a Mozilla-1.1 license that can be
// found in the LICENSE file.
var backgroundPage = chrome.extension.getBackgroundPage();
var defaultTabId = parseInt(location.href.replace(/.*tabid=([0-9]*).*/, '$1'));
function insertTabInfo(tab) {
if (isNaN(defaultTabId)) {
defaultTabId = tab.id;
}
if (uls[tab.id]) {
return;
}
var ul = $('<ul>').appendTo($('#logs_items'));
uls[tab.id] = ul;
var title = tab.title;
if (!title) {
title = 'Tab ' + tab.id;
}
$('<a>').attr('href', '#')
.attr('tabid', tab.id)
.text(title)
.click(function(e) {
loadTabInfo(parseInt($(e.target).attr('tabid')));
}).appendTo(ul);
}
var uls = {};
$(document).ready(function() {
chrome.tabs.query({}, function(tabs) {
for (var i = 0; i < tabs.length; ++i) {
var protocol = tabs[i].url.replace(/(^[^:]*).*/, '$1');
if (protocol != 'http' && protocol != 'https' && protocol != 'file') {
continue;
}
insertTabInfo(tabs[i]);
}
for (var i in backgroundPage.tabStatus) {
insertTabInfo({id: i});
}
$('#tracking').change(function() {
var tabStatus = backgroundPage.tabStatus[currentTab];
if (tabStatus) {
tabStatus.tracking = tracking.checked;
}
});
loadTabInfo(defaultTabId);
});
});
$(document).ready(function() {
$('#beforeSubmit').click(function() {
var link = $('#submitLink');
if (beforeSubmit.checked) {
link.show();
} else {
link.hide();
}
});
});
var currentTab = -1;
function loadTabInfo(tabId) {
if (isNaN(tabId)) {
return;
}
if (tabId != currentTab) {
if (currentTab != -1) {
uls[currentTab].removeClass('selected');
}
currentTab = tabId;
uls[tabId].addClass('selected');
var s = backgroundPage.generateLogFile(tabId);
$('#text').val(s);
tracking.checked = backgroundPage.tabStatus[tabId].tracking;
}
}
| JavaScript |
// Copyright (c) 2012 eagleonhill(qiuc12@gmail.com). All rights reserved.
// Use of this source code is governed by a Mozilla-1.1 license that can be
// found in the LICENSE file.
function ObjectWithEvent() {
this._events = {};
}
ObjectWithEvent.prototype = {
bind: function(name, func) {
if (!Array.isArray(this._events[name])) {
this._events[name] = [];
}
this._events[name].push(func);
},
unbind: function(name, func) {
if (!Array.isArray(this._events[name])) {
return;
}
for (var i = 0; i < this._events[name].length; ++i) {
if (this._events[name][i] == func) {
this._events[name].splice(i, 1);
break;
}
}
},
trigger: function(name, argument) {
if (this._events[name]) {
var handlers = this._events[name];
for (var i = 0; i < handlers.length; ++i) {
handlers[i].apply(this, argument);
}
}
}
};
| JavaScript |
// Copyright (c) 2012 eagleonhill(qiuc12@gmail.com). All rights reserved.
// Use of this source code is governed by a Mozilla-1.1 license that can be
// found in the LICENSE file.
var config;
function loadConfig(_resp) {
config = _resp;
$(document).ready(init);
}
function openPopup() {
var url = chrome.extension.getURL('popup.html?tabid=' + config.tabId);
var windowConfig = 'height=380,width=560,toolbar=no,menubar=no,' +
'scrollbars=no,resizable=no,location=no,status=no';
window.open(url, 'popup', windowConfig);
dismiss();
}
function blockSite() {
chrome.extension.sendRequest(
{command: 'BlockSite', site: config.sitePattern});
dismiss();
}
function dismiss() {
chrome.extension.sendRequest({command: 'DismissNotification'});
}
function init() {
$('#enable').click(openPopup);
$('#close').click(dismiss);
$('#block').click(blockSite);
$('#close').text(config.closeMsg);
$('#enable').text(config.enableMsg);
$('#info').text(config.message);
$('#block').text(config.blockMsg);
}
chrome.extension.sendRequest({command: 'GetNotification'}, loadConfig);
| JavaScript |
// Copyright (c) 2012 eagleonhill(qiuc12@gmail.com). All rights reserved.
// Use of this source code is governed by a Mozilla-1.1 license that can be
// found in the LICENSE file.
// Permission for experimental not given.
var handler = chrome.webRequest;
function onBeforeSendHeaders(details) {
var rule = setting.getFirstMatchedRule(
{href: details.url}, setting.cache.userAgent);
if (!rule || !(rule.userAgent in agents)) {
return {};
}
for (var i = 0; i < details.requestHeaders.length; ++i) {
if (details.requestHeaders[i].name == 'User-Agent') {
details.requestHeaders[i].value = agents[rule.userAgent];
break;
}
}
return {requestHeaders: details.requestHeaders};
}
function registerRequestListener() {
if (!handler) {
return;
}
var filters = {
urls: ['<all_urls>'],
types: ['main_frame', 'sub_frame', 'xmlhttprequest']
};
try {
handler.onBeforeSendHeaders.addListener(
onBeforeSendHeaders, filters, ['requestHeaders', 'blocking']);
} catch (e) {
console.log('Your browser doesn\'t support webRequest');
}
}
| JavaScript |
// Copyright (c) 2012 eagleonhill(qiuc12@gmail.com). All rights reserved.
// Use of this source code is governed by a Mozilla-1.1 license that can be
// found in the LICENSE file.
List.types.input = function(p, prop) {
p[0].listdata = this;
this.p = p;
var input = this.input = $('<input></input>').addClass('valinput');
this.label = $('<span></span>').addClass('valdisp');
this.label.click(function(e) {
setTimeout(function() {
input.focus();
}, 10);
});
this.input.focus(function(e) {
input.select();
});
this.input.keypress(function(e) {
p.trigger('change');
});
this.input.keyup(function(e) {
p.trigger('change');
});
this.input.change(function(e) {
p.trigger('change');
});
p.append(this.input).append(this.label);
};
List.types.input.prototype.__defineSetter__('value', function(val) {
this.input.val(val);
this.label.text(val);
});
List.types.input.prototype.__defineGetter__('value', function() {
return this.input.val();
});
List.types.select = function(p, prop) {
p[0].listdata = this;
this.p = p;
var input = this.input = $('<select></select>').addClass('valinput');
this.label = $('<span></span>').addClass('valdisp');
if (prop.option == 'static') {
this.loadOptions(prop.options);
}
var select = this;
this.input.change(function(e) {
if (p.hasClass('readonly')) {
select.value = select.lastval;
} else {
p.trigger('change');
}
});
this.label.click(function(e) {
setTimeout(function() {
input.focus();
}, 10);
});
p.append(this.input).append(this.label);
};
List.types.select.prototype.loadOptions = function(options) {
this.options = options;
this.mapping = {};
this.input.html('');
for (var i = 0; i < options.length; ++i) {
this.mapping[options[i].value] = options[i].text;
var o = $('<option></option>').val(options[i].value).text(options[i].text);
this.input.append(o);
}
};
List.types.select.prototype.__defineGetter__('value', function() {
return this.input.val();
});
List.types.select.prototype.__defineSetter__('value', function(val) {
this.lastval = val;
this.input.val(val);
this.label.text(this.mapping[val]);
});
List.types.checkbox = function(p, prop) {
p[0].listdata = this;
this.p = p;
var input = this.input = $('<input type="checkbox">').addClass('valcheck');
var box = this;
this.input.change(function(e) {
if (p.hasClass('readonly')) {
box.value = box.lastval;
} else {
p.trigger('change');
}
});
p.append(this.input);
};
List.types.checkbox.prototype.__defineGetter__('value', function() {
return this.input[0].checked;
});
List.types.checkbox.prototype.__defineSetter__('value', function(val) {
this.lastval = val;
this.input[0].checked = val;
});
List.types.button = function(p, prop) {
p[0].listdata = this;
this.p = p;
var input = this.input = $('<button>');
if (prop.caption) {
input.text(prop.caption);
}
input.click(function(e) {
p.trigger('command');
return false;
});
p.append(this.input);
};
List.types.button.prototype.__defineGetter__('value', function() {
return undefined;
});
| JavaScript |
$(document).ready(function() {
var help = 'http://code.google.com/p/np-activex/wiki/ExtensionHelp?wl=';
help = help + $$('wikicode');
$('.help').each(function() {
this.href = help;
});
});
| JavaScript |
// Copyright (c) 2012 eagleonhill(qiuc12@gmail.com). All rights reserved.
// Use of this source code is governed by a Mozilla-1.1 license that can be
// found in the LICENSE file.
var USE_RECORD_GAP = 3 * 60 * 1000; // 3 minutes
var _gaq = window._gaq || [];
_gaq.push(['_setAccount', 'UA-28870762-4']);
_gaq.push(['_trackPageview', location.href.replace(/\?.*$/, '')]);
function initGAS() {
var setting = chrome.extension.getBackgroundPage().setting;
if (setting.misc.tracking) {
var ga = document.createElement('script');
ga.type = 'text/javascript'; ga.async = true;
ga.src = 'https://ssl.google-analytics.com/ga.js';
var s = document.getElementsByTagName('script')[0];
s.parentNode.insertBefore(ga, s);
} else {
// dummy it. Non-debug && non-track
_gaq.push = function() {};
}
}
window.addEventListener('load', initGAS, false);
var useHistory = {};
var issueHistory = {};
function trackCheckSpan(history, item) {
var last = history[item];
if (last && Date.now() - last < USE_RECORD_GAP) {
return false;
}
history[item] = Date.now();
return true;
}
function trackIssue(issue) {
if (!trackCheckSpan(issueHistory, issue.identifier)) {
return;
}
_gaq.push(['_trackEvent', 'usage', 'error', '' + issue.identifier]);
}
function trackVersion(version) {
_gaq.push(['_trackEvent', 'option', 'version', version]);
}
function serializeRule(rule) {
return rule.type[0] + ' ' + rule.value;
}
function trackUse(identifier) {
if (!trackCheckSpan(useHistory, identifier)) {
return;
}
if (identifier.substr(0, 7) == 'custom_') {
var rule = setting.getItem(identifier);
_gaq.push(['_trackEvent', 'usage', 'use-custom', serializeRule(rule)]);
} else {
_gaq.push(['_trackEvent', 'usage', 'use', identifier]);
}
}
var urlHistory = {};
function trackNotUse(url) {
if (!trackCheckSpan(urlHistory, url)) {
return;
}
_gaq.push(['_trackEvent', 'usage', 'notuse', url]);
}
function trackDisable(identifier) {
_gaq.push(['_trackEvent', 'option', 'disable', identifier]);
}
function trackAutoEnable(identifier) {
_gaq.push(['_trackEvent', 'option', 'autoenable', identifier]);
}
function trackEnable(identifier) {
_gaq.push(['_trackEvent', 'option', 'enable', identifier]);
}
function trackAddCustomRule(rule, auto) {
var cmd = 'add';
if (auto) {
cmd = 'add-' + auto;
}
_gaq.push(['_trackEvent', 'option', cmd, serializeRule(rule)]);
}
function trackManualUpdate() {
_gaq.push(['_trackEvent', 'update', 'manual']);
}
function trackUpdateFile(url) {
_gaq.push(['_trackEvent', 'update', 'file', url]);
}
| JavaScript |
var Renren = Renren || {};
if(!Renren.share){
Renren.share = function() {
var isIE = navigator.userAgent.match(/(msie) ([\w.]+)/i);
var hl = location.href.indexOf('#');
var resUrl = (hl == -1 ? location.href : location.href.substr(0, hl));
var shareImgs = "";
var sl = function(str) {
var placeholder = new Array(23).join('x');
str = str
.replace(
/(https?|ftp|gopher|telnet|prospero|wais|nntp){1}:\/\/\w*[\u4E00-\u9FA5]*((?![\"| |\t|\r|\n]).)+/ig,
function(match) {
return placeholder + match.substr(171);
}).replace(/[^\u0000-\u00ff]/g, "xx");
return Math.ceil(str.length / 2);
};
var cssImport = function(){
var static_url = 'http://xnimg.cn/xnapp/share/css/v2/rrshare.css';
var b = document.createElement("link");
b.rel = "stylesheet";
b.type = "text/css";
b.href = static_url;
(document.getElementsByTagName("head")[0] || document.body).appendChild(b)
};
var getShareType = function (dom) {
return dom.getAttribute("type") || "button"
};
var opts = {};
if(typeof(imgMinWidth)!='undefined'){
opts.imgMinWidth = imgMinWidth || 60;
} else {
opts.imgMinWidth = 60;
}
if(typeof(imgMinHeight)!='undefined'){
opts.imgMinHeight = imgMinHeight || 60;
} else {
opts.imgMinHeight = 60;
}
var renderShareButton = function (btn,index) {
if(btn.rendered){
return;
}
btn.paramIndex = index;
var shareType = getShareType(btn).split("_");
var showType = shareType[0] == "icon" ? "icon" : "button";
var size = shareType[1] || "small";
var shs = "xn_share_"+showType+"_"+size;
var innerHtml = [
'<span class="xn_share_wrapper ',shs,'"></span>'
];
btn.innerHTML = innerHtml.join("");
btn.rendered = true;
};
var postTarget = function(opts) {
var form = document.createElement('form');
form.action = opts.url;
form.target = opts.target;
form.method = 'POST';
form.acceptCharset = "UTF-8";
for (var key in opts.params) {
var val = opts.params[key];
if (val !== null && val !== undefined) {
var input = document.createElement('textarea');
input.name = key;
input.value = val;
form.appendChild(input);
}
}
var hidR = document.getElementById('renren-root-hidden');
if (!hidR) {
hidR = document.createElement('div'), syl = hidR.style;
syl.positon = 'absolute';
syl.top = '-10000px';
syl.width = syl.height = '0px';
hidR.id = 'renren-root-hidden';
(document.body || document.getElementsByTagName('body')[0])
.appendChild(hidR);
}
hidR.appendChild(form);
try {
var cst = null;
if (isIE && document.charset.toUpperCase() != 'UTF-8') {
cst = document.charset;
document.charset = 'UTF-8';
}
form.submit();
} finally {
form.parentNode.removeChild(form);
if (cst) {
document.charset = cst;
}
}
};
var getCharSet = function(){
if(document.charset){
return document.charset.toUpperCase();
} else {
var metas = document.getElementsByTagName("meta");
for(var i=0;i < metas.length;i++){
var meta = metas[i];
var metaCharset = meta.getAttribute('charset');
if(metaCharset){
return meta.getAttribute('charset');
}
var metaContent = meta.getAttribute('content');
if(metaContent){
var contenxt = metaContent.toLowerCase();
var begin = contenxt.indexOf("charset=");
if(begin!=-1){
var end = contenxt.indexOf(";",begin+"charset=".length);
if(end != -1){
return contenxt.substring(begin+"charset=".length,end);
}
return contenxt.substring(begin+"charset=".length);
}
}
}
}
return '';
}
var charset = getCharSet();
var getParam = function (param){
param = param || {};
param.api_key = param.api_key || '';
param.resourceUrl = param.resourceUrl || resUrl;
param.title = param.title || '';
param.pic = param.pic || '';
param.description = param.description || '';
if(resUrl == param.resourceUrl){
param.images = param.images || shareImgs;//一般就是当前页面的分享,因此取当前页面的img
}
param.charset = param.charset || charset || '';
return param;
}
var onclick = function(data) {
var submitUrl = 'http://widget.renren.com/dialog/share';
var p = getParam(data);
var prm = [];
for (var i in p) {
if (p[i])
prm.push(i + '=' + encodeURIComponent(p[i]));
}
var url = submitUrl+"?" + prm.join('&'), maxLgh = (isIE ? 2048 : 4100), wa = 'width=700,height=650,left=0,top=0,resizable=yes,scrollbars=1';
if (url.length > maxLgh) {
window.open('about:blank', 'fwd', wa);
postTarget({
url : submitUrl,
target : 'fwd',
params : p
});
} else {
window.open(url, 'fwd', wa);
}
return false;
};
window["rrShareOnclick"] = onclick;
var init = function() {
if (Renren.share.isReady || document.readyState !== 'complete')
return;
var imgs = document.getElementsByTagName('img'), imga = [];
for (var i = 0; i < imgs.length; i++) {
if (imgs[i].width >= opts.imgMinWidth
&& imgs[i].height >= opts.imgMinHeight) {
imga.push(imgs[i].src);
}
}
window["rrShareImgs"] = imga;
if (imga.length > 0)
shareImgs = imga.join('|');
if (document.addEventListener) {
document.removeEventListener('DOMContentLoaded', init, false);
} else {
document.detachEvent('onreadystatechange', init);
}
cssImport();
var shareBtn = document.getElementsByName("xn_share");
var len = shareBtn?shareBtn.length:0;
for (var b = 0; b < len; b++) {
var a = shareBtn[b];
renderShareButton(a,b);
}
Renren.share.isReady = true;
};
if (document.readyState === 'complete') {
init();
} else if (document.addEventListener) {
document.addEventListener('DOMContentLoaded', init, false);
window.addEventListener('load', init, false);
} else {
document.attachEvent('onreadystatechange', init);
window.attachEvent('onload', init);
}
};
}
| JavaScript |
// Copyright (c) 2012 eagleonhill(qiuc12@gmail.com). All rights reserved.
// Use of this source code is governed by a Mozilla-1.1 license that can be
// found in the LICENSE file.
var background = chrome.extension.getBackgroundPage();
var setting = background.setting;
var updateSession = background.updateSession;
function toggleRule(e) {
var line = e.data.line;
var index = line.attr('row');
var item = setting.order[index];
if (item.position == 'default') {
if (item.status == 'enabled') {
item.status = 'disabled';
trackDisable(item.identifier);
} else if (item.status == 'disabled') {
item.status = 'enabled';
trackEnable(item.identifier);
}
}
line.blur();
e.data.list.finishEdit(line);
e.data.list.updateLine(line);
save();
}
var settingProps = [{
header: '',
property: 'status',
type: 'button',
caption: '',
events: {
command: toggleRule,
update: setStatus,
createNew: setStatusNew
}
}, {
header: $$('title'),
property: 'title',
type: 'input'
}, {
header: $$('mode'),
property: 'type',
type: 'select',
option: 'static',
options: [
{value: 'wild', text: $$('WildChar')},
{value: 'regex', text: $$('RegEx')},
{value: 'clsid', text: $$('CLSID')}
]
}, {
header: $$('pattern'),
property: 'value',
type: 'input'
}, {
header: $$('user_agent'),
property: 'userAgent',
type: 'select',
option: 'static',
options: [
{value: '', text: 'Chrome'},
{value: 'ie9', text: 'MSIE9'},
{value: 'ie8', text: 'MSIE8'},
{value: 'ie7', text: 'MSIE7'},
{value: 'ff7win', text: 'Firefox 7'},
{value: 'ip5', text: 'iPhone'},
{value: 'ipad5', text: 'iPad'}
]
}, {
header: $$('helper_script'),
property: 'script',
type: 'input'
}
];
var table;
var dirty = false;
function save() {
dirty = true;
}
function doSave() {
if (dirty) {
dirty = false;
setting.update();
}
}
function setReadonly(e) {
var line = e.data.line;
var id = line.attr('row');
if (id < 0) {
return;
}
var order = setting.order[id];
var divs = $('.listvalue', line);
if (order.position != 'custom') {
divs.addClass('readonly');
} else {
divs.removeClass('readonly');
}
}
$(window).blur(doSave);
function refresh() {
table.refresh();
}
// Main setting
$(document).ready(function() {
table = new List({
props: settingProps,
main: $('#tbSetting'),
lineEvents: {
update: setReadonly
},
getItems: function() {
return setting.order;
},
getItemProp: function(i, prop) {
if (prop in setting.order[i]) {
return setting.order[i][prop];
}
return setting.getItem(setting.order[i])[prop];
},
setItemProp: function(i, prop, value) {
if (prop in setting.order[i]) {
setting.order[i][prop] = value;
} else {
setting.getItem(setting.order[i])[prop] = value;
}
},
defaultValue: setting.createRule(),
count: function() {
return setting.order.length;
},
insert: function(id, newItem) {
setting.addCustomRule(newItem);
this.move(setting.order.length - 1, id);
},
remove: function(id) {
if (setting.order[id].position != 'custom') {
return true;
}
var identifier = setting.order[id].identifier;
delete setting.rules[identifier];
setting.order.splice(id, 1);
},
validate: function(id, rule) {
return setting.validateRule(rule);
}
});
$(table).bind('updated', save);
$('#addRule').bind('click', function() {
table.editNewLine();
});
$(table).bind('select', function() {
var line = table.selectedLine;
if (line < 0) {
$('#moveUp').attr('disabled', 'disabled');
$('#moveDown').attr('disabled', 'disabled');
$('#deleteRule').attr('disabled', 'disabled');
} else {
if (line != 0) {
$('#moveUp').removeAttr('disabled');
} else {
$('#moveUp').attr('disabled', 'disabled');
}
if (line != setting.order.length - 1) {
$('#moveDown').removeAttr('disabled');
} else {
$('#moveDown').attr('disabled', 'disabled');
}
if (setting.order[line].position != 'custom') {
$('#deleteRule').attr('disabled', 'disabled');
} else {
$('#deleteRule').removeAttr('disabled');
}
}
});
$('#moveUp').click(function() {
var line = table.selectedLine;
table.move(line, line - 1, true);
});
$('#moveDown').click(function() {
var line = table.selectedLine;
table.move(line, line + 1, true);
});
$('#deleteRule').click(function() {
var line = table.selectedLine;
table.remove(line);
});
table.init();
updateSession.bind('update', refresh);
});
window.onbeforeunload = function() {
updateSession.unbind('update', refresh);
};
function setStatusNew(e) {
with (e.data) {
s = 'Custom';
color = '#33f';
$('button', line).text(s).css('background-color', color);
}
}
function setStatus(e) {
with (e.data) {
var id = line.attr('row');
var order = setting.order[id];
var rule = setting.getItem(order);
var s, color;
if (order.status == 'enabled') {
s = $$('Enabled');
color = '#0A0';
} else if (order.status == 'disabled') {
s = $$('Disabled');
color = 'indianred';
} else {
s = $$('Custom');
color = '#33f';
}
$('button', line).text(s).css('background-color', color);
}
}
function showTime(time) {
var never = 'Never';
if (time == 0) {
return never;
}
var delta = Date.now() - time;
if (delta < 0) {
return never;
}
function getDelta(delta) {
var sec = delta / 1000;
if (sec < 60) {
return [sec, 'second'];
}
var minute = sec / 60;
if (minute < 60) {
return [minute, 'minute'];
}
var hour = minute / 60;
if (hour < 60) {
return [hour, 'hour'];
}
var day = hour / 24;
return [day, 'day'];
}
var disp = getDelta(delta);
var v1 = Math.floor(disp[0]);
return v1 + ' ' + disp[1] + (v1 != 1 ? 's' : '') + ' ago';
}
$(document).ready(function() {
$('#log_enable').change(function(e) {
setting.misc.logEnabled = e.target.checked;
save();
})[0].checked = setting.misc.logEnabled;
$('#tracking').change(function(e) {
setting.misc.tracking = e.target.checked;
save();
})[0].checked = setting.misc.tracking;
});
$(document).ready(function() {
var help = 'http://code.google.com/p/np-activex/wiki/ExtensionHelp?wl=';
help = help + $$('wikicode');
$('.help').each(function() {
this.href = help;
});
});
$(window).load(function() {
if (background.firstUpgrade) {
background.firstUpgrade = false;
alert($$('upgrade_show'));
}
});
| JavaScript |
// Copyright (c) 2012 eagleonhill(qiuc12@gmail.com). All rights reserved.
// Use of this source code is governed by a Mozilla-1.1 license that can be
// found in the LICENSE file.
var FLASH_CLSID = '{d27cdb6e-ae6d-11cf-96b8-444553540000}';
var typeId = 'application/x-itst-activex';
var updating = false;
function executeScript(script) {
var scriptobj = document.createElement('script');
scriptobj.innerHTML = script;
var element = document.head || document.body ||
document.documentElement || document;
element.insertBefore(scriptobj, element.firstChild);
element.removeChild(scriptobj);
}
function checkParents(obj) {
var parent = obj;
var level = 0;
while (parent && parent.nodeType == 1) {
if (getComputedStyle(parent).display == 'none') {
var desp = obj.id + ' at level ' + level;
if (scriptConfig.none2block) {
parent.style.display = 'block';
parent.style.height = '0px';
parent.style.width = '0px';
log('Remove display:none for ' + desp);
} else {
log('Warning: Detected display:none for ' + desp);
}
}
parent = parent.parentNode;
++level;
}
}
function getLinkDest(url) {
if (typeof url != 'string') {
return url;
}
url = url.trim();
if (/^https?:\/\/.*/.exec(url)) {
return url;
}
if (url[0] == '/') {
if (url[1] == '/') {
return location.protocol + url;
} else {
return location.origin + url;
}
}
return location.href.replace(/\/[^\/]*$/, '/' + url);
}
var hostElement = null;
function enableobj(obj) {
updating = true;
// We can't use classid directly because it confuses the browser.
obj.setAttribute('clsid', getClsid(obj));
obj.removeAttribute('classid');
checkParents(obj);
if (!scriptConfig.activate_inplace) {
log('Create replacement object');
var oldObj = obj;
obj = obj.cloneNode(true);
// Remove all script nodes. They're executed.
var scripts = obj.getElementsByTagName('script');
for (var i = 0; i < scripts.length; ++i) {
scripts[i].parentNode.removeChild(scripts[i]);
}
} else {
log('activate inplace');
}
// Set codebase to full path.
var codebase = obj.getAttribute('codebase');
if (codebase && codebase != '') {
obj.setAttribute('codebase', getLinkDest(codebase));
}
obj.activex_process = true;
obj.type = typeId;
if (!scriptConfig.activate_inplace) {
oldObj.parentNode.insertBefore(obj, oldObj);
obj.parentNode.removeChild(oldObj);
}
if (obj.id) {
var command = '';
if (obj.form && scriptConfig.formid) {
var form = obj.form.name;
command += 'document.all.' + form + '.' + obj.id;
command += ' = document.all.' + obj.id + ';\n';
log('Set form[obj.id]: form: ' + form + ', object: ' + obj.id);
}
// Allow access by document.obj.id
if (obj.id && scriptConfig.documentid) {
command += 'delete document.' + obj.id + ';\n';
command += 'document.' + obj.id + '=' + obj.id + ';\n';
}
if (command) {
executeScript(command);
}
}
log('Enabled object, id: ' + obj.id + ' clsid: ' + getClsid(obj));
updating = false;
return obj;
}
function getClsid(obj) {
if (obj.hasAttribute('clsid'))
return obj.getAttribute('clsid');
var clsid = obj.getAttribute('classid');
var compos = clsid.indexOf(':');
if (clsid.substring(0, compos).toLowerCase() != 'clsid')
return;
clsid = clsid.substring(compos + 1);
return '{' + clsid + '}';
}
function notify(data) {
connect();
data.command = 'DetectControl';
port.postMessage(data);
}
function process(obj) {
if (obj.activex_process) {
return;
}
if (onBeforeLoading.caller == enableobj ||
onBeforeLoading.caller == process ||
onBeforeLoading.caller == checkParents) {
log('Nested onBeforeLoading ' + obj.id);
return;
}
if (obj.type == typeId) {
if (!config || !config.pageRule) {
// hack??? Deactive this object.
log('Deactive unexpected object ' + obj.outerHTML);
return true;
}
log('Found objects created by client scripts');
notify({
href: location.href,
clsid: clsid,
actived: true,
rule: config.pageRule.identifier
});
obj.activex_process = true;
return;
}
if ((obj.type != '' && obj.type != 'application/x-oleobject') ||
!obj.hasAttribute('classid')) {
log('object with no clsid');
return;
}
if (getClsid(obj).toLowerCase() == FLASH_CLSID) {
return;
}
if (config == null) {
// Delay the process of this object.
// Hope config will be load soon.
log('Pending object ', obj.id);
pendingObjects.push(obj);
return;
}
obj.activex_process = true;
connect();
var clsid = getClsid(obj);
var rule = config.shouldEnable({href: location.href, clsid: clsid});
if (rule) {
log('Object activating');
obj = enableobj(obj);
notify({
href: location.href,
clsid: clsid,
actived: true,
rule: rule.identifier
});
} else {
notify({href: location.href, clsid: clsid, actived: false});
log('Object not activated');
}
}
function replaceSubElements(obj) {
var s = obj.querySelectorAll('object[classid]');
if (obj.tagName == 'OBJECT' && obj.hasAttribute('classid')) {
s.push(obj);
}
for (var i = 0; i < s.length; ++i) {
process(s[i]);
}
}
function onBeforeLoading(event) {
var obj = event.target;
if (obj.nodeName == 'OBJECT') {
log('BeforeLoading ' + obj.id);
if (process(obj)) {
event.preventDefault();
}
}
}
function onError(event) {
var message = 'Error: ';
message += event.message;
message += ' at ';
message += event.filename;
message += ':';
message += event.lineno;
log(message);
return false;
}
function setUserAgent() {
if (!config.pageRule) {
return;
}
var agent = getUserAgent(config.pageRule.userAgent);
if (agent && agent != '') {
log('Set userAgent: ' + config.pageRule.userAgent);
var js = '(function(agent) {';
js += 'delete navigator.userAgent;';
js += 'navigator.userAgent = agent;';
js += 'delete navigator.appVersion;';
js += "navigator.appVersion = agent.substr(agent.indexOf('/') + 1);";
js += "if (agent.indexOf('MSIE') >= 0) {";
js += 'delete navigator.appName;';
js += 'navigator.appName = "Microsoft Internet Explorer";}})("';
js += agent;
js += '")';
executeScript(js);
}
}
function onSubtreeModified(e) {
if (updating) {
return;
}
if (e.nodeType == e.TEXT_NODE) {
return;
}
replaceSubElements(e.srcElement);
}
| JavaScript |
document.addEventListener('DOMContentLoaded', function() {
if (window.PocoUpload) {
document.all.PocoUpload.Document = document;
}
}, false); | JavaScript |
scriptConfig.formid = true;
| JavaScript |
(function(proto) {
proto.__defineGetter__("classid", function() {
var clsid = this.getAttribute("clsid");
if (clsid == null) {
return "";
}
return "CLSID:" + clsid.substring(1, clsid.length - 1);
})
proto.__defineSetter__("classid", function(value) {
var e = document.createEvent('TextEvent');
e.initTextEvent(
'__npactivex_log_event__', false, false, window,
'edit clsid ' + value);
window.dispatchEvent(e);
var oldstyle = this.style.display;
this.style.display = "none";
var pos = value.indexOf(":");
this.setAttribute("clsid", "{" + value.substring(pos + 1) + "}");
this.setAttribute("type", "application/x-itst-activex");
this.style.display = oldstyle;
})
})(HTMLObjectElement.prototype);
| JavaScript |
scriptConfig.none2block = true;
| JavaScript |
(function () {
var hiddenDivId = "__hiddendiv_activex";
window.__proto__.ActiveXObject = function(progid) {
progid = progid.trim();
var e = document.createEvent('TextEvent');
e.initTextEvent(
'__npactivex_log_event__', false, false, window,
'Dynamic create ' + progid);
window.dispatchEvent(e);
if (progid == 'Msxml2.XMLHTTP' || progid == 'Microsoft.XMLHTTP')
return new XMLHttpRequest();
var hiddenDiv = document.getElementById(hiddenDivId);
if (!hiddenDiv) {
if (!document.body) return null;
hiddenDiv = document.createElement("div");
hiddenDiv.id = hiddenDivId;
hiddenDiv.setAttribute("style", "width:0px; height:0px");
document.body.insertBefore(hiddenDiv, document.body.firstChild)
}
var obj = document.createElement("object");
obj.setAttribute("type", "application/x-itst-activex");
obj.setAttribute("progid", progid);
obj.setAttribute("style", "width:0px; height:0px");
obj.setAttribute("dynamic", "");
hiddenDiv.appendChild(obj);
if (obj.object === undefined) {
throw new Error('Dynamic create failed ' + progid)
}
return obj.object
}
//console.log("ActiveXObject declared");
})();
| JavaScript |
window.addEventListener('load', function() {Exobud.URL = objMmInfo[0].mmUrl}, false); | JavaScript |
(function(node) {
node.createPopup = node.createPopup || function() {
var SetElementStyles = function(element, styleDict) {
var style = element.style;
for (var styleName in styleDict) {
style[styleName] = styleDict[styleName];
}
}
var eDiv = document.createElement('div');
SetElementStyles(eDiv, {
'position': 'absolute',
'top': 0 + 'px',
'left': 0 + 'px',
'width': 0 + 'px',
'height': 0 + 'px',
'zIndex': 1000,
'display': 'none',
'overflow': 'hidden'
});
eDiv.body = eDiv;
eDiv.write = function(string) {
eDiv.innerHTML += string;
}
var opened = false;
var setOpened = function(b) {
opened = b;
}
var getOpened = function() {
return opened;
}
var getCoordinates = function(oElement) {
var coordinates = {
x: 0,
y: 0
};
while (oElement) {
coordinates.x += oElement.offsetLeft;
coordinates.y += oElement.offsetTop;
oElement = oElement.offsetParent;
}
return coordinates;
}
return {
htmlTxt: '',
document: eDiv,
isOpen: getOpened(),
isShow: false,
hide: function() {
SetElementStyles(eDiv, {
'top': 0 + 'px',
'left': 0 + 'px',
'width': 0 + 'px',
'height': 0 + 'px',
'display': 'none'
});
eDiv.innerHTML = '';
this.isShow = false;
},
show: function(iX, iY, iWidth, iHeight, oElement) {
if (!getOpened()) {
document.body.appendChild(eDiv);
setOpened(true);
};
this.htmlTxt = eDiv.innerHTML;
if (this.isShow) {
this.hide();
};
eDiv.innerHTML = this.htmlTxt;
var coordinates = getCoordinates(oElement);
eDiv.style.top = (iX + coordinates.x) + 'px';
eDiv.style.left = (iY + coordinates.y) + 'px';
eDiv.style.width = iWidth + 'px';
eDiv.style.height = iHeight + 'px';
eDiv.style.display = 'block';
this.isShow = true;
}
}
}
})(window.__proto__);
| JavaScript |
(function (doc) {
doc.createElement = function(orig) {
return function(name) {
if (name.trim()[0] == '<') {
// We assume the name is correct.
document.head.innerHTML += name;
var obj = document.head.lastChild;
document.head.removeChild(obj);
return obj;
} else {
var val = orig.call(this, name);
if (name == "object") {
val.setAttribute("type", "application/x-itst-activex");
}
return val;
}
}
}(doc.createElement);
})(HTMLDocument.prototype);
| JavaScript |
(function() {
function reload() {
var maps = document.getElementsByTagName("map");
for (var i = 0; i < maps.length; ++i) {
if (maps[i].name == "") maps[i].name = maps[i].id;
}
}
if (document.readyState == 'complete') {
reload();
} else {
window.addEventListener('load', reload, false);
}
})(); | JavaScript |
navigator.cpuClass='x86';
| JavaScript |
window.addEventListener('load', function() {
delete FrmUserInfo.elements;
FrmUserInfo.elements = function(x){return this[x]};
console.log('cloudzz patch');
onAuthenticated();
}, false);
HTMLElement.prototype.insertAdjacentHTML = function(orig) {
return function() {
this.style.display = "block";
this.style.overflow = "hidden";
orig.apply(this, arguments);
}
}(HTMLElement.prototype.insertAdjacentHTML); | JavaScript |
(function() {
function declareEventAsIE(node) {
if (!node.attachEvent) {
node.attachEvent = function(event, operation) {
if (event.substr(0, 2) == "on") this.addEventListener(event.substr(2), operation, false)
}
}
if (!node.detachEvent) {
node.detachEvent = function(event, operation) {
if (event.substr(0, 2) == "on") this.removeEventListener(event.substr(2), operation, false)
}
}
}
declareEventAsIE(window.Node.prototype);
declareEventAsIE(window.__proto__);
})();
| JavaScript |
(function() {
Document.prototype.getElementById = function(orig) {
return function(id) {
var a = this.getElementsByName(id);
if (a.length > 0) {
return a[0];
}
return orig.call(this, id);
}
} (Document.prototype.getElementById);
})();
| JavaScript |
document.addEventListener('DOMContentLoaded', function() {
if (window.doLogin && window.statcus && window.psw) {
function makeHidden(obj) {
obj.style.display = 'block';
obj.style.height = '0px';
obj.style.width = '0px';
}
window.doLogin = function(orig) {
return function() {
if (statcus.style.display == 'none') {
makeHidden(statcus);
}
if (psw.style.display == 'none') {
makeHidden(psw);
}
orig();
};
}(doLogin);
}
}, false);
| JavaScript |
(function () {
function patch() {
if (window.ShowPayPage && window.InitControls) {
InitControls = function(orig) {
return function() {
if (CreditCardYear.object === undefined) {
CreditCardYear.object = {};
}
if (CreditCardMonth.object === undefined) {
CreditCardMonth.object = {};
}
if (CreditCardCVV2.object === undefined) {
CreditCardCVV2.object = {};
}
orig();
}
} (InitControls);
ShowPayPage = function(orig) {
return function(par) {
orig(par);
InitControls();
}
} (ShowPayPage);
DoSubmit = function(orig) {
return function(par) {
if (!CardPayNo.Option) {
CardPayNo.Option = function() {};
}
orig(par);
}
} (DoSubmit);
}
if (window.OpenWnd) {
var inputs = document.querySelectorAll('div > input[type=hidden]');
for (var i = 0; i < inputs.length; ++i) {
window[inputs[i].name] = inputs[i];
}
}
function patchLoginSwitch(fncName) {
if (!(window[fncName])) {
return;
}
window[fncName] = function(orig) {
return function(par) {
orig(par);
MobileNo_Ctrl.PasswdCtrl = false;
EMail_Ctrl.PasswdCtrl = false;
NetBankUser_Ctrl.PasswdCtrl = false;
DebitCardNo_Ctrl.PasswdCtrl = false;
CreditCardNo_Ctrl.PasswdCtrl = false;
IdNo_Ctrl.PasswdCtrl = false;
BookNo_Ctrl.PasswdCtrl = false;
}
} (window[fncName]);
}
patchLoginSwitch('changeCreditCardLoginType');
patchLoginSwitch('changeEALoginType');
patchLoginSwitch('showLoginEntry');
CallbackCheckClient = function() {};
}
if (document.readyState == 'complete') {
patch();
} else {
window.addEventListener('load', patch, false);
}
})();
| JavaScript |
scriptConfig.activate_inplace = true;
| JavaScript |
window.addEventListener('DOMContentLoaded', function() {
if (window.logonSubmit) {
logonSubmit = function(orig) {
return function() {
try {
orig();
} catch (e) {
if (e.message == 'Error calling method on NPObject.') {
// We assume it has passed the checking.
frmLogon.submit();
clickBoolean = false;
}
}
}
}(logonSubmit);
}
}, false);
| JavaScript |
scriptConfig.documentid = true;
| JavaScript |
window.addEventListener('load', function(){
if (IE_FingerPrint)
IE_FingerPrint = FingerPrint;
}, false);
| JavaScript |
window.addEventListener('error', function(event) {
function executeScript(file) {
var request = new XMLHttpRequest();
// In case it needs immediate loading, use sync ajax.
request.open('GET', file, false);
request.send();
eval(translate(request.responseText));
}
function translate(text) {
text = text.replace(/function ([\w]+\.[\w\.]+)\(/, "$1 = function (");
return text;
}
if (event.message == 'Uncaught SyntaxError: Unexpected token .') {
executeScript(event.filename);
}
}, true);
| JavaScript |
(function() {
function __bugupatch() {
if (typeof cntv != 'undefined') {
cntv.player.util.getPlayerCore = function(orig) {
return function() {
var ret = orig();
if (arguments.callee.caller.toString().indexOf('GetPlayerControl') != -1) {
return {
GetVersion: ret.GetVersion,
GetPlayerControl: ret.GetPlayerControl()
};
} else {
return ret;
};
}
} (cntv.player.util.getPlayerCore);
console.log('buguplayer patched');
window.removeEventListener('beforeload', __bugupatch, true);
}
}
window.addEventListener('beforeload', __bugupatch, true);
})() | JavaScript |
function initShare() {
var link = 'https://chrome.google.com/webstore/detail/' +
'lgllffgicojgllpmdbemgglaponefajn';
var text2 = ['Chrome也能用网银啦!',
'每次付款还要换浏览器?你out啦!',
'现在可以彻底抛弃IE了!',
'让IE去死吧!',
'Chrome用网银:'
];
text2 = text2[Math.floor(Math.random() * 1000121) % text2.length];
text2 = '只要安装了ActiveX for Chrome,就可以直接在Chrome里' +
'使用各种网银、播放器等ActiveX控件了。而且不用切换内核,非常方便。';
var pic = 'http://ww3.sinaimg.cn/bmiddle/8c75b426jw1dqz2l1qfubj.jpg';
var text = text2 + '下载地址:';
// facebook
(function(d, s, id) {
var js, fjs = d.getElementsByTagName(s)[0];
if (d.getElementById(id)) return;
js = d.createElement(s); js.id = id;
js.src = 'https://connect.facebook.net/en_US/all.js#xfbml=1';
js.async = true;
fjs.parentNode.insertBefore(js, fjs);
}(document, 'script', 'facebook-jssdk'));
window.___gcfg = {lang: navigator.language};
// Google plus
(function() {
var po = document.createElement('script');
po.type = 'text/javascript'; po.async = true;
po.src = 'https://apis.google.com/js/plusone.js';
var s = document.getElementsByTagName('script')[0];
s.parentNode.insertBefore(po, s);
})();
// Sina weibo
(function() {
var _w = 75 , _h = 24;
var param = {
url: link,
type: '2',
count: '1', /**是否显示分享数,1显示(可选)*/
appkey: '798098327', /**您申请的应用appkey,显示分享来源(可选)*/
title: text,
pic: pic, /**分享图片的路径(可选)*/
ralateUid: '2356524070', /**关联用户的UID,分享微博会@该用户(可选)*/
language: 'zh_cn', /**设置语言,zh_cn|zh_tw(可选)*/
rnd: new Date().valueOf()
};
var temp = [];
for (var p in param) {
temp.push(p + '=' + encodeURIComponent(param[p] || ''));
}
weiboshare.innerHTML = '<iframe allowTransparency="true"' +
' frameborder="0" scrolling="no" ' +
'src="http://hits.sinajs.cn/A1/weiboshare.html?' +
temp.join('&') + '" width="' + _w + '" height="' + _h + '"></iframe>';
})();
//renren
function shareClick() {
var rrShareParam = {
resourceUrl: link,
pic: pic,
title: 'Chrome用网银:ActiveX for Chrome',
description: text2
};
rrShareOnclick(rrShareParam);
}
Renren.share();
xn_share.addEventListener('click', shareClick, false);
// Tencent weibo
function postToWb() {
var _url = encodeURIComponent(link);
var _assname = encodeURI('');
var _appkey = encodeURI('801125118');//你从腾讯获得的appkey
var _pic = encodeURI(pic);
var _t = '';
var metainfo = document.getElementsByTagName('meta');
for (var metai = 0; metai < metainfo.length; metai++) {
if ((new RegExp('description', 'gi')).test(
metainfo[metai].getAttribute('name'))) {
_t = metainfo[metai].attributes['content'].value;
}
}
_t = text;
if (_t.length > 120) {
_t = _t.substr(0, 117) + '...';
}
_t = encodeURI(_t);
var _u = 'http://share.v.t.qq.com/index.php?c=share&a=index&url=' + _url +
'&appkey=' + _appkey + '&pic=' + _pic + '&assname=' + _assname +
'&title=' + _t;
window.open(_u, '', 'width=700, height=680, top=0, left=0, toolbar=no,' +
' menubar=no, scrollbars=no, location=yes, resizable=no, status=no');
}
qqweibo.addEventListener('click', postToWb, false);
// Douban
function doubanShare() {
var d = document,
e = encodeURIComponent,
s1 = window.getSelection,
s2 = d.getSelection,
s3 = d.selection,
s = s1 ? s1() : s2 ? s2() : s3 ? s3.createRange().text : '',
r = 'http://www.douban.com/recommend/?url=' + e(link) +
'&title=' + e('ActiveX for Chrome') + '&sel=' + e(s) + '&v=1';
window.open(
r, 'douban',
'toolbar=0,resizable=1,scrollbars=yes,status=1,width=450,height=330');
}
doubanshare.addEventListener('click', doubanShare, false);
}
$(document).ready(function() {
div = $('#share');
div.load('share.html', function() {
setTimeout(initShare, 200);
});
});
document.write('<script type="text/javascript" src="rrshare.js"></script>');
document.write('<div id="share">');
document.write('</div>');
| JavaScript |
// Copyright (c) 2012 eagleonhill(qiuc12@gmail.com). All rights reserved.
// Use of this source code is governed by a Mozilla-1.1 license that can be
// found in the LICENSE file.
/*
prop = {
header, // String
property, // String
events, //
type, // checkbox, select, input.type, button
extra // depend on type
}
*/
function List(config) {
this.config = config;
this.props = config.props;
this.main = config.main;
this.selectedLine = -2;
this.lines = [];
if (!config.getItems) {
config.getItems = function() {
return config.items;
}
}
if (!config.getItemProp) {
config.getItemProp = function(id, prop) {
return config.getItem(id)[prop];
}
}
if (!config.setItemProp) {
config.setItemProp = function(id, prop, value) {
config.getItem(id)[prop] = value;
}
}
if (!config.getItem) {
config.getItem = function(id) {
return config.getItems()[id];
}
}
if (!config.move) {
config.move = function(a, b) {
if (a != b && a >= 0 && b >= 0 && a < this.count() && b < this.count()) {
var list = config.getItems();
var tmp = list[a];
// remove a
list.splice(a, 1);
// insert b
list.splice(b, 0, tmp);
}
}
}
if (!config.insert) {
config.insert = function(id, newItem) {
config.getItems().splice(id, 0, newItem);
}
}
if (!config.remove) {
config.remove = function(a) {
config.move(a, config.count() - 1);
config.getItems().pop();
}
}
if (!config.validate) {
config.validate = function() {return true;};
}
if (!config.count) {
config.count = function() {
return config.getItems().length;
}
}
if (!config.patch) {
config.patch = function(id, newVal) {
for (var name in newVal) {
config.setItemProp(id, name, newVal[name]);
}
}
}
if (!config.defaultValue) {
config.defaultValue = {};
}
config.main.addClass('list');
}
List.ids = {
noline: -1
};
List.types = {};
List.prototype = {
init: function() {
with (this) {
if (this.inited) {
return;
}
this.inited = true;
this.headergroup = $('<div class="headers"></div>');
for (var i = 0; i < props.length; ++i) {
var header = $('<div class="header"></div>').
attr('property', props[i].property).html(props[i].header);
headergroup.append(header);
}
this.scrolls = $('<div>').addClass('listscroll');
this.contents = $('<div class="listitems"></div>').appendTo(scrolls);
scrolls.scroll(function() {
headergroup.css('left', -(scrolls.scrollLeft()) + 'px');
});
contents.click(function(e) {
if (e.target == contents[0]) {
selectLine(List.ids.noline);
}
});
$(main).append(headergroup).append(scrolls);
var height = this.main.height() - this.headergroup.outerHeight();
this.scrolls.height(height);
load();
selectLine(List.ids.noline);
}
},
editNewLine: function() {
this.startEdit(this.lines[this.lines.length - 1]);
},
updatePropDisplay: function(line, prop) {
var name = prop.property;
obj = $('[property=' + name + ']', line);
var ctrl = obj[0].listdata;
var id = Number(line.attr('row'));
if (id == this.config.count()) {
var value = this.config.defaultValue[name];
if (value) {
ctrl.value = value;
}
obj.trigger('createNew');
} else {
ctrl.value = this.config.getItemProp(id, name);
obj.trigger('update');
}
},
updateLine: function(line) {
for (var i = 0; i < this.props.length; ++i) {
this.updatePropDisplay(line, this.props[i]);
}
if (Number(line.attr('row')) < this.config.count()) {
line.trigger('update');
} else {
line.addClass('newline');
}
},
createLine: function() {
with (this) {
var line = $('<div></div>').addClass('itemline');
var inner = $('<div>');
line.append(inner);
// create input boxes
for (var i = 0; i < props.length; ++i) {
var prop = props[i];
var ctrl = $('<div></div>').attr('property', prop.property)
.addClass('listvalue').attr('tabindex', -1);
var valueobj = new List.types[prop.type](ctrl, prop);
var data = {list: this, line: line, prop: prop};
for (var e in prop.events) {
ctrl.bind(e, data, prop.events[e]);
}
ctrl.bind('change', function(e) {
validate(line);
return true;
});
ctrl.bind('keyup', function(e) {
if (e.keyCode == 27) {
cancelEdit(line);
}
});
ctrl.trigger('create');
inner.append(ctrl);
}
// Event listeners
line.click(function(e) {
startEdit(line);
});
line.focusin(function(e) {
startEdit(line);
});
line.focusout(function(e) {
finishEdit(line);
});
for (var e in this.config.lineEvents) {
line.bind(e, {list: this, line: line}, this.config.lineEvents[e]);
}
var list = this;
line.bind('updating', function() {
$(list).trigger('updating');
});
line.bind('updated', function() {
$(list).trigger('updated');
});
this.bindId(line, this.lines.length);
this.lines.push(line);
line.appendTo(this.contents);
return line;
}
},
refresh: function(lines) {
var all = false;
if (lines === undefined) {
all = true;
lines = [];
}
for (var i = this.lines.length; i <= this.config.count(); ++i) {
var line = this.createLine();
lines.push(i);
}
while (this.lines.length > this.config.count() + 1) {
this.lines.pop().remove();
}
$('.newline', this.contents).removeClass('newline');
this.lines[this.lines.length - 1].addClass('newline');
if (all) {
for (var i = 0; i < this.lines.length; ++i) {
this.updateLine(this.lines[i]);
}
} else {
for (var i = 0; i < lines.length; ++i) {
this.updateLine(this.lines[lines[i]]);
}
}
},
load: function() {
this.contents.empty();
this.lines = [];
this.refresh();
},
bindId: function(line, id) {
line.attr('row', id);
},
getLineNewValue: function(line) {
var ret = {};
for (var i = 0; i < this.props.length; ++i) {
this.getPropValue(line, ret, this.props[i]);
}
return ret;
},
getPropValue: function(line, item, prop) {
var name = prop.property;
obj = $('[property=' + name + ']', line);
var ctrl = obj[0].listdata;
var value = ctrl.value;
if (value !== undefined) {
item[name] = value;
}
return value;
},
startEdit: function(line) {
if (line.hasClass('editing')) {
return;
}
line.addClass('editing');
this.showLine(line);
this.selectLine(line);
var list = this;
setTimeout(function() {
if (!line[0].contains(document.activeElement)) {
$('.valinput', line).first().focus();
}
list.validate(line);
}, 50);
},
finishEdit: function(line) {
var list = this;
function doFinishEdit() {
with (list) {
if (line[0].contains(document.activeElement)) {
return;
}
var valid = isValid(line);
if (valid) {
var id = Number(line.attr('row'));
var newval = getLineNewValue(line);
if (line.hasClass('newline')) {
$(list).trigger('updating');
if (!config.insert(id, newval)) {
line.removeClass('newline');
list.selectLine(line);
$(list).trigger('add', id);
addNewLine();
}
} else {
line.trigger('updating');
config.patch(id, newval);
}
line.trigger('updated');
}
cancelEdit(line);
}
};
setTimeout(doFinishEdit, 50);
},
cancelEdit: function(line) {
line.removeClass('editing');
line.removeClass('error');
var id = Number(line.attr('row'));
if (id == this.config.count() && this.selectedLine == id) {
this.selectedLine = List.ids.noline;
}
this.updateLine(line);
},
addNewLine: function() {
with (this) {
var line = $('.newline', contents);
if (!line.length) {
line = createLine().addClass('newline');
}
return line;
}
},
isValid: function(line) {
var id = Number(line.attr('row'));
var obj = this.getLineNewValue(line);
return valid = this.config.validate(id, obj);
},
validate: function(line) {
if (this.isValid(line)) {
line.removeClass('error');
} else {
line.addClass('error');
}
},
move: function(a, b, keepSelect) {
var len = this.config.count();
if (a == b || a < 0 || b < 0 || a >= len || b >= len) {
return;
}
this.config.move(a, b);
for (var i = Math.min(a, b); i <= Math.max(a, b); ++i) {
this.updateLine(this.getLine(i));
}
if (keepSelect) {
if (this.selectedLine == a) {
this.selectLine(b);
} else if (this.selectedLine == b) {
this.selectLine(a);
}
}
},
getLine: function(id) {
if (id < 0 || id >= this.lines.length) {
return null;
}
return this.lines[id];
},
remove: function(id) {
id = Number(id);
if (id < 0 || id >= this.config.count()) {
return;
}
$(this).trigger('updating');
var len = this.lines.length;
this.getLine(id).trigger('removing');
if (this.config.remove(id)) {
return;
}
this.getLine(len - 1).remove();
this.lines.pop();
for (var i = id; i < len - 1; ++i) {
this.updateLine(this.getLine(i));
}
if (id >= len - 2) {
this.selectLine(id);
} else {
this.selectLine(List.ids.noline);
}
$(this).trigger('updated');
},
selectLine: function(id) {
var line = id;
if (typeof id == 'number') {
line = this.getLine(id);
} else {
id = Number(line.attr('row'));
}
// Can't select the new line.
if (line && line.hasClass('newline')) {
line = null;
id = List.ids.noline;
}
if (this.selectedLine == id) {
return;
}
var oldline = this.getLine(this.selectedLine);
if (oldline) {
this.cancelEdit(oldline);
oldline.removeClass('selected');
oldline.trigger('deselect');
this.selectedLine = List.ids.noline;
}
this.selectedLine = id;
if (line != null) {
line.addClass('selected');
line.trigger('select');
this.showLine(line);
}
$(this).trigger('select');
},
showLine: function(line) {
var showtop = this.scrolls.scrollTop();
var showbottom = showtop + this.scrolls.height();
var top = line.offset().top - this.contents.offset().top;
// Include the scroll bar
var bottom = top + line.height() + 20;
if (top < showtop) {
// show at top
this.scrolls.scrollTop(top);
} else if (bottom > showbottom) {
// show at bottom
this.scrolls.scrollTop(Math.max(0, bottom - this.scrolls.height()));
}
}
};
| JavaScript |
// Copyright (c) 2012 eagleonhill(qiuc12@gmail.com). All rights reserved.
// Use of this source code is governed by a Mozilla-1.1 license that can be
// found in the LICENSE file.
List.types.input = function(p, prop) {
p[0].listdata = this;
this.p = p;
var input = this.input = $('<input></input>').addClass('valinput');
this.label = $('<span></span>').addClass('valdisp');
this.label.click(function(e) {
setTimeout(function(){
input.focus();
}, 10);
});
this.input.focus(function(e) {
input.select();
});
this.input.keypress(function(e) {
p.trigger('change');
});
this.input.keyup(function(e) {
p.trigger('change');
});
this.input.change(function(e) {
p.trigger('change');
});
p.append(this.input).append(this.label);
};
List.types.input.prototype.__defineSetter__('value', function(val) {
this.input.val(val);
this.label.text(val);
});
List.types.input.prototype.__defineGetter__('value', function() {
return this.input.val();
});
List.types.select = function(p, prop) {
p[0].listdata = this;
this.p = p;
var input = this.input = $('<select></select>').addClass('valinput');
this.label = $('<span></span>').addClass('valdisp');
if (prop.option == 'static') {
this.loadOptions(prop.options);
}
var select = this;
this.input.change(function(e) {
if (p.hasClass('readonly')) {
select.value = select.lastval;
} else {
p.trigger('change');
}
});
this.label.click(function(e) {
setTimeout(function(){
input.focus();
}, 10);
});
p.append(this.input).append(this.label);
};
List.types.select.prototype.loadOptions = function(options) {
this.options = options;
this.mapping = {};
this.input.html("");
for (var i = 0; i < options.length; ++i) {
this.mapping[options[i].value] = options[i].text;
var o = $('<option></option>').val(options[i].value).text(options[i].text)
this.input.append(o);
}
}
List.types.select.prototype.__defineGetter__('value', function() {
return this.input.val();
});
List.types.select.prototype.__defineSetter__('value', function(val) {
this.lastval = val;
this.input.val(val);
this.label.text(this.mapping[val]);
});
List.types.checkbox = function(p, prop) {
p[0].listdata = this;
this.p = p;
var input = this.input = $('<input type="checkbox">').addClass('valcheck');
var box = this;
this.input.change(function(e) {
if (p.hasClass('readonly')) {
box.value = box.lastval;
} else {
p.trigger('change');
}
});
p.append(this.input);
};
List.types.checkbox.prototype.__defineGetter__('value', function() {
return this.input[0].checked;
});
List.types.checkbox.prototype.__defineSetter__('value', function(val) {
this.lastval = val;
this.input[0].checked = val;
});
List.types.button = function(p, prop) {
p[0].listdata = this;
this.p = p;
var input = this.input = $('<button>');
if (prop.caption) {
input.text(prop.caption);
}
input.click(function(e) {
p.trigger('command');
return false;
});
p.append(this.input);
};
List.types.button.prototype.__defineGetter__('value', function() {
return undefined;
});
| JavaScript |
// Copyright (c) 2012 eagleonhill(qiuc12@gmail.com). All rights reserved.
// Use of this source code is governed by a Mozilla-1.1 license that can be
// found in the LICENSE file.
var baseDir = '/setting/';
var rules = [];
var scripts = [];
var issues = [];
var dirty = false;
function setScriptAutoComplete(e) {
var last = /[^\s]*$/;
var obj = $('input', e.target);
$(obj).bind("keydown", function(event) {
if (event.keyCode === $.ui.keyCode.TAB &&
$(this).data("autocomplete").menu.active) {
event.preventDefault();
}
})
.autocomplete({
minLength: 0,
source: function(request, response) {
// delegate back to autocomplete, but extract the last term
response($.ui.autocomplete.filter(
scriptItems, last.exec(request.term)[0]));
},
focus: function() {
// prevent value inserted on focus
return false;
},
select: function(event, ui) {
this.value = this.value.replace(last, ui.item.value);
return false;
}
});
}
var ruleProps = [ {
header: "Identifier",
property: "identifier",
type: "input"
}, {
header: "Name",
property: "title",
type: "input"
}, {
header: "Mode",
property: "type",
type: "select",
option: "static",
options: [
{value: "wild", text: "WildChar"},
{value: "regex", text: "RegEx"},
{value: "clsid", text: "CLSID"}
]
}, {
header: "Pattern",
property: "value",
type: "input"
}, {
header: "Keyword",
property: "keyword",
type: "input"
}, {
header: "testURL",
property: "testUrl",
type: "input"
}, {
header: "UserAgent",
property: "userAgent",
type: "select",
option: "static",
options: [
{value: "", text: "Chrome"},
{value: "ie9", text: "MSIE9"},
{value: "ie8", text: "MSIE8"},
{value: "ie7", text: "MSIE7"},
{value: "ff7win", text: "Firefox 7 Windows"},
{value: "ff7mac", text: "Firefox 7 Mac"},
{value: "ip5", text: "iPhone"},
{value: "ipad5", text: "iPad"}
]
}, {
header: "Helper Script",
property: "script",
type: "input",
events: {
create: setScriptAutoComplete
}
}];
var currentScript = -1;
function showScript(id) {
var url = baseDir + scripts[id].url;
currentScript = id;
$(scriptEditor).val('');
$.ajax(url, {
success: function(value) {
origScript = value;
$(scriptEditor).val(value);
}
});
$('#scriptDialog').dialog('open');
}
function saveToFile(file, value) {
$.ajax(baseDir + 'upload.php', {
type: "POST",
data: {
file: file,
data: value
}
});
}
var origScript;
function saveScript(id) {
var value = $('#scriptEditor').val();
if (value == origScript) {
return;
}
var file = scripts[id].url;
scriptList.updateLine(scriptList.getLine(id));
saveToFile(file, value);
dirty = true;
}
var scriptProps = [{
property: "identifier",
header: "Identifier",
type: "input"
}, {
property: "url",
header: "URL",
type: "input"
}, {
property: "context",
header: "Context",
type: "select",
option: "static",
options: [
{value: "page", text: "Page"},
{value: "extension", text: "Extension"}
]
}, {
property: "show",
header: "Show",
type: "button",
events: {
create: function(e) {
$('button', this).text('Show');
},
command: function(e) {
showScript(Number(e.data.line.attr('row')), true);
}
}
}];
var issueProps = [{
header: "Identifier",
property: "identifier",
type: "input"
}, {
header: "Mode",
property: "type",
type: "select",
option: "static",
options: [
{value: "wild", text: "WildChar"},
{value: "regex", text: "RegEx"},
{value: "clsid", text: "CLSID"}
]
}, {
header: "Pattern",
property: "value",
type: "input"
}, {
header: "Description",
property: "description",
type: "input"
}, {
header: "IssueId",
property: "issueId",
type: "input"
}, {
header: "url",
property: "url",
type: "input"
}];
// The JSON formatter is from http://joncom.be/code/javascript-json-formatter/
function FormatJSON(oData, sIndent) {
function RealTypeOf(v) {
if (typeof(v) == "object") {
if (v === null) return "null";
if (v.constructor == Array) return "array";
if (v.constructor == Date) return "date";
if (v.constructor == RegExp) return "regex";
return "object";
}
return typeof(v);
}
if (arguments.length < 2) {
var sIndent = "";
}
var sIndentStyle = " ";
var sDataType = RealTypeOf(oData);
// open object
if (sDataType == "array") {
if (oData.length == 0) {
return "[]";
}
var sHTML = "[";
} else {
var iCount = 0;
$.each(oData, function() {
iCount++;
return;
});
if (iCount == 0) { // object is empty
return "{}";
}
var sHTML = "{";
}
// loop through items
var iCount = 0;
$.each(oData, function(sKey, vValue) {
if (iCount > 0) {
sHTML += ",";
}
if (sDataType == "array") {
sHTML += ("\n" + sIndent + sIndentStyle);
} else {
sHTML += ("\n" + sIndent + sIndentStyle + "\"" + sKey + "\"" + ": ");
}
// display relevant data type
switch (RealTypeOf(vValue)) {
case "array":
case "object":
sHTML += FormatJSON(vValue, (sIndent + sIndentStyle));
break;
case "boolean":
case "number":
sHTML += vValue.toString();
break;
case "null":
sHTML += "null";
break;
case "string":
sHTML += ("\"" + vValue + "\"");
break;
default:
sHTML += JSON.stringify(vValue);
}
// loop
iCount++;
});
// close object
if (sDataType == "array") {
sHTML += ("\n" + sIndent + "]");
} else {
sHTML += ("\n" + sIndent + "}");
}
// return
return sHTML;
}
function loadRules(value) {
rules = [];
for (var i in value) {
rules.push(value[i]);
}
ruleList.refresh();
freezeIdentifier(ruleList);
}
function loadIssues(value) {
issues = [];
for (var i in value) {
issues.push(value[i]);
}
issueList.refresh();
freezeIdentifier(issueList);
}
function loadScripts(value) {
scripts = [];
for (var i in value) {
scripts.push(value[i]);
}
scriptList.refresh();
freezeIdentifier(scriptList);
updateScriptItems();
}
function serialize(list) {
var obj = {};
for (var i = 0; i < list.length; ++i) {
obj[list[i].identifier] = list[i];
}
return FormatJSON(obj);
}
function save() {
saveToFile('setting.json', serialize(rules));
saveToFile('scripts.json', serialize(scripts));
saveToFile('issues.json', serialize(issues));
dirty= false;
freezeIdentifier(ruleList);
freezeIdentifier(scriptList);
}
function reload() {
$.ajax(baseDir + 'setting.json', {
success: loadRules
});
$.ajax(baseDir + 'scripts.json', {
success: loadScripts
});
$.ajax(baseDir + 'issues.json', {
success: loadIssues
});
dirty = false;
}
function freezeIdentifier(list) {
$('.itemline:not(.newline) div[property=identifier]', list.contents)
.addClass('readonly');
}
var scriptList, ruleList, issueList;
var scriptItems = [];
function updateScriptItems() {
scriptItems = [];
for (var i = 0; i < scripts.length; ++i) {
scriptItems.push(scripts[i].identifier);
}
}
$(document).ready(function() {
window.onbeforeunload=function() {
if (dirty) {
return 'Page not saved. Continue?';
}
}
$('#addRule').click(function() {
ruleList.editNewLine();
}).button();
$('#deleteRule').click(function() {
ruleList.remove(ruleList.selectedLine);
}).button();
$('#addScript').click(function() {
scriptList.editNewLine();
}).button();
$('#deleteScript').click(function() {
scriptList.remove(scriptList.selectedLine);
}).button();
$('#addIssue').click(function() {
issueList.editNewLine();
}).button();
$('#deleteIssue').click(function() {
issueList.remove(issueList.selectedLine);
}).button();
$('.doSave').each(function() {
$(this).click(save).button();
});
$('#tabs').tabs();
$('#scriptDialog').dialog({
modal: true,
autoOpen: false,
height: 500,
width: 700,
buttons: {
"Save": function() {
saveScript(currentScript);
$(this).dialog('close');
},
"Cancel": function() {
$(this).dialog('close');
}
}
});
$.ajaxSetup({
cache: false
});
scriptList = new List({
props: scriptProps,
main: $('#scriptTable'),
getItems: function() {return scripts;}
});
$(scriptList).bind('updated', function() {
dirty = true;
updateScriptItems();
});
scriptList.init();
ruleList = new List({
props: ruleProps,
main: $('#ruleTable'),
getItems: function() {return rules;}
});
ruleList.init();
$(ruleList).bind('updated', function() {
dirty = true;
});
issueList = new List({
props: issueProps,
main: $('#issueTable'),
getItems: function() {return issues;}
});
issueList.init();
$(issueList).bind('updated', function() {
dirty = true;
});
reload();
});
| JavaScript |
// Copyright (c) 2012 eagleonhill(qiuc12@gmail.com). All rights reserved.
// Use of this source code is governed by a Mozilla-1.1 license that can be
// found in the LICENSE file.
/*
prop = {
header, // String
property, // String
events, //
type, // checkbox, select, input.type, button
extra // depend on type
}
*/
function List(config) {
this.config = config;
this.props = config.props;
this.main = config.main;
this.selectedLine = -2;
this.lines = [];
if (!config.getItems) {
config.getItems = function() {
return config.items;
}
}
if (!config.getItemProp) {
config.getItemProp = function(id, prop) {
return config.getItem(id)[prop];
}
}
if (!config.setItemProp) {
config.setItemProp = function(id, prop, value) {
config.getItem(id)[prop] = value;
}
}
if (!config.getItem) {
config.getItem = function(id) {
return config.getItems()[id];
}
}
if (!config.move) {
config.move = function(a, b) {
if (a != b && a >= 0 && b >= 0 && a < this.count() && b < this.count()) {
var list = config.getItems();
var tmp = list[a];
// remove a
list.splice(a, 1);
// insert b
list.splice(b, 0, tmp);
}
}
};
if (!config.insert) {
config.insert = function(id, newItem) {
config.getItems().splice(id, 0, newItem);
}
}
if (!config.remove) {
config.remove = function(a) {
config.move(a, config.count() - 1);
config.getItems().pop();
}
}
if (!config.validate) {
config.validate = function() {return true;};
}
if (!config.count) {
config.count = function() {
return config.getItems().length;
}
}
if (!config.patch) {
config.patch = function(id, newVal) {
for (var name in newVal) {
config.setItemProp(id, name, newVal[name]);
}
}
}
if (!config.defaultValue) {
config.defaultValue = {};
}
config.main.addClass('list');
}
List.ids = {
noline: -1,
};
List.types = {};
List.prototype = {
init: function() {
with (this) {
if (this.inited) {
return;
}
this.inited = true;
this.headergroup = $('<div class="headers"></div>');
for (var i = 0; i < props.length; ++i) {
var header = $('<div class="header"></div>').
attr('property', props[i].property).html(props[i].header);
headergroup.append(header);
}
this.scrolls = $('<div>').addClass('listscroll');
this.contents = $('<div class="listitems"></div>').appendTo(scrolls);
scrolls.scroll(function() {
headergroup.css('left', -(scrolls.scrollLeft()) + 'px');
});
contents.click(function(e) {
if (e.target == contents[0]) {
selectLine(List.ids.noline);
}
});
$(main).append(headergroup).append(scrolls);
var height = this.main.height() - this.headergroup.outerHeight();
this.scrolls.height(height);
load();
selectLine(List.ids.noline);
}
},
editNewLine: function() {
this.startEdit(this.lines[this.lines.length - 1]);
},
updatePropDisplay : function(line, prop) {
var name = prop.property;
obj = $('[property=' + name + ']', line);
var ctrl = obj[0].listdata;
var id = Number(line.attr('row'));
if (id == this.config.count()) {
var value = this.config.defaultValue[name];
if (value) {
ctrl.value = value;
}
obj.trigger('createNew');
} else {
ctrl.value = this.config.getItemProp(id, name);
obj.trigger('update');
}
},
updateLine: function(line) {
for (var i = 0; i < this.props.length; ++i) {
this.updatePropDisplay(line, this.props[i]);
}
if (Number(line.attr('row')) < this.config.count()) {
line.trigger('update');
} else {
line.addClass('newline');
}
},
createLine: function() {
with (this) {
var line = $('<div></div>').addClass('itemline');
var inner = $('<div>');
line.append(inner);
// create input boxes
for (var i = 0; i < props.length; ++i) {
var prop = props[i];
var ctrl = $('<div></div>').attr('property', prop.property)
.addClass('listvalue').attr('tabindex', -1);
var valueobj = new List.types[prop.type](ctrl, prop);
var data = {list: this, line: line, prop: prop};
for (var e in prop.events) {
ctrl.bind(e, data, prop.events[e]);
}
ctrl.bind('change', function(e) {
validate(line);
return true;
});
ctrl.bind('keyup', function(e) {
if (e.keyCode == 27) {
cancelEdit(line);
}
});
ctrl.trigger('create');
inner.append(ctrl);
}
// Event listeners
line.click(function(e) {
startEdit(line);
});
line.focusin(function(e) {
startEdit(line);
});
line.focusout(function(e) {
finishEdit(line);
});
for (var e in this.config.lineEvents) {
line.bind(e, {list: this, line: line}, this.config.lineEvents[e]);
}
var list = this;
line.bind('updating', function() {
$(list).trigger('updating');
});
line.bind('updated', function() {
$(list).trigger('updated');
});
this.bindId(line, this.lines.length);
this.lines.push(line);
line.appendTo(this.contents);
return line;
}
},
refresh: function(lines) {
var all = false;
if (lines === undefined) {
all = true;
lines = [];
}
for (var i = this.lines.length; i <= this.config.count(); ++i) {
var line = this.createLine();
lines.push(i);
}
while (this.lines.length > this.config.count() + 1) {
this.lines.pop().remove();
}
$('.newline', this.contents).removeClass('newline');
this.lines[this.lines.length - 1].addClass('newline');
if (all) {
for (var i = 0; i < this.lines.length; ++i) {
this.updateLine(this.lines[i]);
}
} else {
for (var i = 0; i < lines.length; ++i) {
this.updateLine(this.lines[lines[i]]);
}
}
},
load: function() {
this.contents.empty();
this.lines = [];
this.refresh();
},
bindId: function(line, id) {
line.attr('row', id);
},
getLineNewValue: function(line) {
var ret = {};
for (var i = 0; i < this.props.length; ++i) {
this.getPropValue(line, ret, this.props[i]);
}
return ret;
},
getPropValue: function(line, item, prop) {
var name = prop.property;
obj = $('[property=' + name + ']', line);
var ctrl = obj[0].listdata;
var value = ctrl.value;
if (value !== undefined) {
item[name] = value;
}
return value;
},
startEdit: function(line) {
if (line.hasClass('editing')) {
return;
}
line.addClass('editing');
this.showLine(line);
this.selectLine(line);
var list = this;
setTimeout(function() {
if (!line[0].contains(document.activeElement)) {
$('.valinput', line).first().focus();
}
list.validate(line);
}, 50);
},
finishEdit: function(line) {
var list = this;
function doFinishEdit() {
with(list) {
if (line[0].contains(document.activeElement)) {
return;
}
var valid = isValid(line);
if (valid) {
var id = Number(line.attr('row'));
var newval = getLineNewValue(line);
if (line.hasClass('newline')) {
$(list).trigger('updating');
if(!config.insert(id, newval)) {
line.removeClass('newline');
list.selectLine(line);
$(list).trigger('add', id);
addNewLine();
}
} else {
line.trigger('updating');
config.patch(id, newval);
}
line.trigger('updated');
}
cancelEdit(line);
}
};
setTimeout(doFinishEdit, 50);
},
cancelEdit: function(line) {
line.removeClass('editing');
line.removeClass('error');
var id = Number(line.attr('row'));
if (id == this.config.count() && this.selectedLine == id) {
this.selectedLine = List.ids.noline;
}
this.updateLine(line);
},
addNewLine: function() {
with(this) {
var line = $('.newline', contents);
if (!line.length) {
line = createLine().addClass('newline');
}
return line;
}
},
isValid: function(line) {
var id = Number(line.attr('row'));
var obj = this.getLineNewValue(line);
return valid = this.config.validate(id, obj);
},
validate: function(line) {
if (this.isValid(line)) {
line.removeClass('error');
} else {
line.addClass('error');
}
},
move: function(a, b, keepSelect) {
var len = this.config.count();
if (a == b || a < 0 || b < 0 || a >= len || b >= len) {
return;
}
this.config.move(a, b);
for (var i = Math.min(a, b); i <= Math.max(a, b); ++i) {
this.updateLine(this.getLine(i));
}
if (keepSelect) {
if (this.selectedLine == a) {
this.selectLine(b);
} else if (this.selectedLine == b) {
this.selectLine(a);
}
}
},
getLine: function(id) {
if (id < 0 || id >= this.lines.length) {
return null;
}
return this.lines[id];
},
remove: function(id) {
id = Number(id);
if (id < 0 || id >= this.config.count()) {
return;
}
$(this).trigger('updating');
var len = this.lines.length;
this.getLine(id).trigger('removing');
if (this.config.remove(id)) {
return;
}
this.getLine(len - 1).remove();
this.lines.pop();
for (var i = id; i < len - 1; ++i) {
this.updateLine(this.getLine(i));
}
if (id >= len - 2) {
this.selectLine(id);
} else {
this.selectLine(List.ids.noline);
}
$(this).trigger('updated');
},
selectLine: function(id) {
var line = id;
if (typeof id == "number") {
line = this.getLine(id);
} else {
id = Number(line.attr('row'));
}
// Can't select the new line.
if (line && line.hasClass('newline')) {
line = null;
id = List.ids.noline;
}
if (this.selectedLine == id) {
return;
}
var oldline = this.getLine(this.selectedLine);
if (oldline) {
this.cancelEdit(oldline);
oldline.removeClass('selected');
oldline.trigger('deselect');
this.selectedLine = List.ids.noline;
}
this.selectedLine = id;
if (line != null) {
line.addClass('selected');
line.trigger('select');
this.showLine(line);
}
$(this).trigger('select');
},
showLine: function(line) {
var showtop = this.scrolls.scrollTop();
var showbottom = showtop + this.scrolls.height();
var top = line.offset().top - this.contents.offset().top;
// Include the scroll bar
var bottom = top + line.height() + 20;
if (top < showtop) {
// show at top
this.scrolls.scrollTop(top);
} else if (bottom > showbottom) {
// show at bottom
this.scrolls.scrollTop(Math.max(0, bottom - this.scrolls.height()));
}
}
};
| JavaScript |
/*
* Superfish v1.4.8 - jQuery menu widget
* Copyright (c) 2008 Joel Birch
*
* Dual licensed under the MIT and GPL licenses:
* http://www.opensource.org/licenses/mit-license.html
* http://www.gnu.org/licenses/gpl.html
*
* CHANGELOG: http://users.tpg.com.au/j_birch/plugins/superfish/changelog.txt
*/
;(function($){
$.fn.superfish = function(op){
var sf = $.fn.superfish,
c = sf.c,
$arrow = $(['<span class="',c.arrowClass,'"> »</span>'].join('')),
over = function(){
var $$ = $(this), menu = getMenu($$);
clearTimeout(menu.sfTimer);
$$.showSuperfishUl().siblings().hideSuperfishUl();
},
out = function(){
var $$ = $(this), menu = getMenu($$), o = sf.op;
clearTimeout(menu.sfTimer);
menu.sfTimer=setTimeout(function(){
o.retainPath=($.inArray($$[0],o.$path)>-1);
$$.hideSuperfishUl();
if (o.$path.length && $$.parents(['li.',o.hoverClass].join('')).length<1){over.call(o.$path);}
},o.delay);
},
getMenu = function($menu){
var menu = $menu.parents(['ul.',c.menuClass,':first'].join(''))[0];
sf.op = sf.o[menu.serial];
return menu;
},
addArrow = function($a){ $a.addClass(c.anchorClass).append($arrow.clone()); };
return this.each(function() {
var s = this.serial = sf.o.length;
var o = $.extend({},sf.defaults,op);
o.$path = $('li.'+o.pathClass,this).slice(0,o.pathLevels).each(function(){
$(this).addClass([o.hoverClass,c.bcClass].join(' '))
.filter('li:has(ul)').removeClass(o.pathClass);
});
sf.o[s] = sf.op = o;
$('li:has(ul)',this)[($.fn.hoverIntent && !o.disableHI) ? 'hoverIntent' : 'hover'](over,out).each(function() {
if (o.autoArrows) addArrow( $('>a:first-child',this) );
})
.not('.'+c.bcClass)
.hideSuperfishUl();
var $a = $('a',this);
$a.each(function(i){
var $li = $a.eq(i).parents('li');
$a.eq(i).focus(function(){over.call($li);}).blur(function(){out.call($li);});
});
o.onInit.call(this);
}).each(function() {
var menuClasses = [c.menuClass];
if (sf.op.dropShadows && !($.browser.msie && $.browser.version < 7)) menuClasses.push(c.shadowClass);
$(this).addClass(menuClasses.join(' '));
});
};
var sf = $.fn.superfish;
sf.o = [];
sf.op = {};
sf.IE7fix = function(){
var o = sf.op;
if ($.browser.msie && $.browser.version > 6 && o.dropShadows && o.animation.opacity!=undefined)
this.toggleClass(sf.c.shadowClass+'-off');
};
sf.c = {
bcClass : 'sf-breadcrumb',
menuClass : 'sf-js-enabled',
anchorClass : 'sf-with-ul',
arrowClass : 'ui-icon-carat-1-s ui-icon',
shadowClass : 'sf-shadow'
};
sf.defaults = {
hoverClass : 'sfHover',
pathClass : 'overideThisToUse',
pathLevels : 1,
delay : 200,
animation : {opacity:'show'},
speed : 'fast',
autoArrows : true,
dropShadows : true,
disableHI : false, // true disables hoverIntent detection
onInit : function(){}, // callback functions
onBeforeShow: function(){},
onShow : function(){},
onHide : function(){}
};
$.fn.extend({
hideSuperfishUl : function(){
var o = sf.op,
not = (o.retainPath===true) ? o.$path : '';
o.retainPath = false;
var $ul = $(['li.',o.hoverClass].join(''),this).add(this).not(not).removeClass(o.hoverClass)
.find('>ul').hide().css('visibility','hidden');
o.onHide.call($ul);
return this;
},
showSuperfishUl : function(){
var o = sf.op,
sh = sf.c.shadowClass+'-off',
$ul = this.addClass(o.hoverClass)
.find('>ul:hidden').css('visibility','visible');
sf.IE7fix.call($ul);
o.onBeforeShow.call($ul);
$ul.animate(o.animation,o.speed,function(){ sf.IE7fix.call($ul); o.onShow.call($ul); });
return this;
}
});
})(jQuery); | JavaScript |
/**
* Cookie plugin
*
* Copyright (c) 2006 Klaus Hartl (stilbuero.de)
* Dual licensed under the MIT and GPL licenses:
* http://www.opensource.org/licenses/mit-license.php
* http://www.gnu.org/licenses/gpl.html
*
*/
/**
* Create a cookie with the given name and value and other optional parameters.
*
* @example $.cookie('the_cookie', 'the_value');
* @desc Set the value of a cookie.
* @example $.cookie('the_cookie', 'the_value', { expires: 7, path: '/', domain: 'jquery.com', secure: true });
* @desc Create a cookie with all available options.
* @example $.cookie('the_cookie', 'the_value');
* @desc Create a session cookie.
* @example $.cookie('the_cookie', null);
* @desc Delete a cookie by passing null as value. Keep in mind that you have to use the same path and domain
* used when the cookie was set.
*
* @param String name The name of the cookie.
* @param String value The value of the cookie.
* @param Object options An object literal containing key/value pairs to provide optional cookie attributes.
* @option Number|Date expires Either an integer specifying the expiration date from now on in days or a Date object.
* If a negative value is specified (e.g. a date in the past), the cookie will be deleted.
* If set to null or omitted, the cookie will be a session cookie and will not be retained
* when the the browser exits.
* @option String path The value of the path atribute of the cookie (default: path of page that created the cookie).
* @option String domain The value of the domain attribute of the cookie (default: domain of page that created the cookie).
* @option Boolean secure If true, the secure attribute of the cookie will be set and the cookie transmission will
* require a secure protocol (like HTTPS).
* @type undefined
*
* @name $.cookie
* @cat Plugins/Cookie
* @author Klaus Hartl/klaus.hartl@stilbuero.de
*/
/**
* Get the value of a cookie with the given name.
*
* @example $.cookie('the_cookie');
* @desc Get the value of a cookie.
*
* @param String name The name of the cookie.
* @return The value of the cookie.
* @type String
*
* @name $.cookie
* @cat Plugins/Cookie
* @author Klaus Hartl/klaus.hartl@stilbuero.de
*/
jQuery.cookie = function(name, value, options) {
if (typeof value != 'undefined') { // name and value given, set cookie
options = options || {};
if (value === null) {
value = '';
options = $.extend({}, options); // clone object since it's unexpected behavior if the expired property were changed
options.expires = -1;
}
var expires = '';
if (options.expires && (typeof options.expires == 'number' || options.expires.toUTCString)) {
var date;
if (typeof options.expires == 'number') {
date = new Date();
date.setTime(date.getTime() + (options.expires * 24 * 60 * 60 * 1000));
} else {
date = options.expires;
}
expires = '; expires=' + date.toUTCString(); // use expires attribute, max-age is not supported by IE
}
// NOTE Needed to parenthesize options.path and options.domain
// in the following expressions, otherwise they evaluate to undefined
// in the packed version for some reason...
var path = options.path ? '; path=' + (options.path) : '';
var domain = options.domain ? '; domain=' + (options.domain) : '';
var secure = options.secure ? '; secure' : '';
document.cookie = [name, '=', encodeURIComponent(value), expires, path, domain, secure].join('');
} else { // only name given, get cookie
var cookieValue = null;
if (document.cookie && document.cookie != '') {
var cookies = document.cookie.split(';');
for (var i = 0; i < cookies.length; i++) {
var cookie = jQuery.trim(cookies[i]);
// Does this cookie string begin with the name we want?
if (cookie.substring(0, name.length + 1) == (name + '=')) {
cookieValue = decodeURIComponent(cookie.substring(name.length + 1));
break;
}
}
}
return cookieValue;
}
}; | JavaScript |
$(document).ready(function() {
// Navigation menu
$('ul#navigation').superfish({
delay: 1000,
animation: {opacity:'show',height:'show'},
speed: 'fast',
autoArrows: true,
dropShadows: false
});
$('ul#navigation li').hover(function(){
$(this).addClass('sfHover2');
},
function(){
$(this).removeClass('sfHover2');
});
// Accordion
$("#accordion, #accordion2").accordion({ header: "h3" });
// Tabs
$('#tabs, #tabs2, #tabs5').tabs();
// Dialog
$('#dialog').dialog({
autoOpen: false,
width: 600,
bgiframe: false,
modal: false,
buttons: {
"Ok": function() {
$(this).dialog("close");
},
"Cancel": function() {
$(this).dialog("close");
}
}
});
// Login Dialog Link
$('#login_dialog').click(function(){
$('#login').dialog('open');
return false;
});
// Login Dialog
$('#login').dialog({
autoOpen: false,
width: 300,
height: 230,
bgiframe: true,
modal: true,
buttons: {
"Login": function() {
$(this).dialog("close");
},
"Close": function() {
$(this).dialog("close");
}
}
});
// Dialog Link
$('#dialog_link').click(function(){
$('#dialog').dialog('open');
return false;
});
// Dialog auto open
$('#welcome').dialog({
autoOpen: true,
width: 470,
height: 180,
bgiframe: true,
modal: true,
buttons: {
"View Admintasia V1.0": function() {
$(this).dialog("close");
}
}
});
// Dialog auto open
$('#welcome_login').dialog({
autoOpen: true,
width: 370,
height: 430,
bgiframe: true,
modal: true,
buttons: {
"Proceed to demo !": function() {
window.location = "index.php";
}
}
});
// Datepicker
$('#datepicker').datepicker({
inline: true
});
//Hover states on the static widgets
$('#dialog_link, ul#icons li').hover(
function() { $(this).addClass('ui-state-hover'); },
function() { $(this).removeClass('ui-state-hover'); }
);
//Sortable
$(".column").sortable({
connectWith: '.column'
});
//Sidebar only sortable boxes
$(".side-col").sortable({
axis: 'y',
connectWith: '.side-col'
});
$(".portlet").addClass("ui-widget ui-widget-content ui-helper-clearfix ui-corner-all")
.find(".portlet-header")
.addClass("ui-widget-header")
.prepend('<span class="ui-icon ui-icon-circle-arrow-s"></span>')
.end()
.find(".portlet-content");
$(".portlet-header .ui-icon").click(function() {
$(this).toggleClass("ui-icon-circle-arrow-n");
$(this).parents(".portlet:first").find(".portlet-content").slideToggle();
});
$(".column").disableSelection();
/* Table Sorter */
$("#sort-table")
.tablesorter({
widgets: ['zebra'],
headers: {
// assign the secound column (we start counting zero)
0: {
// disable it by setting the property sorter to false
sorter: false
},
// assign the third column (we start counting zero)
6: {
// disable it by setting the property sorter to false
sorter: false
}
}
})
.tablesorterPager({container: $("#pager")});
$(".header").append('<span class="ui-icon ui-icon-carat-2-n-s"></span>');
});
/* Tooltip */
$(function() {
$('.tooltip').tooltip({
track: true,
delay: 0,
showURL: false,
showBody: " - ",
fade: 250
});
});
/* Theme changer - set cookie */
$(function() {
$("link[title='style']").attr("href","css/styles/default/ui.css");
$('a.set_theme').click(function() {
var theme_name = $(this).attr("id");
$("link[title='style']").attr("href","css/styles/" + theme_name + "/ui.css");
$.cookie('theme', theme_name );
$('a.set_theme').css("fontWeight","normal");
$(this).css("fontWeight","bold");
});
var theme = $.cookie('theme');
if (theme == 'default') {
$("link[title='style']").attr("href","css/styles/default/ui.css");
};
if (theme == 'light_blue') {
$("link[title='style']").attr("href","css/styles/light_blue/ui.css");
};
/* Layout option - Change layout from fluid to fixed with set cookie */
$("#fluid_layout a").click (function(){
$("#fluid_layout").hide();
$("#fixed_layout").show();
$("#page-wrapper").removeClass('fixed');
$.cookie('layout', 'fluid' );
});
$("#fixed_layout a").click (function(){
$("#fixed_layout").hide();
$("#fluid_layout").show();
$("#page-wrapper").addClass('fixed');
$.cookie('layout', 'fixed' );
});
var layout = $.cookie('layout');
if (layout == 'fixed') {
$("#fixed_layout").hide();
$("#fluid_layout").show();
$("#page-wrapper").addClass('fixed');
};
if (layout == 'fluid') {
$("#fixed_layout").show();
$("#fluid_layout").hide();
$("#page-wrapper").addClass('fluid');
};
});
/* Check all table rows */
var checkflag = "false";
function check(field) {
if (checkflag == "false") {
for (i = 0; i < field.length; i++) {
field[i].checked = true;}
checkflag = "true";
return "check_all"; }
else {
for (i = 0; i < field.length; i++) {
field[i].checked = false; }
checkflag = "false";
return "check_none"; }
}
checked=false;
function checkedAll (frm1) {
var aa= document.getElementById('UserList');
if (checked == false)
{
checked = true;
}
else
{
checked = false;
}
for (var i =0; i < aa.elements.length; i++)
{
aa.elements[i].checked = checked;
}
}
| JavaScript |
(function($) {
$.extend({
tablesorterPager: new function() {
function updatePageDisplay(c) {
var s = $(c.cssPageDisplay,c.container).val((c.page+1) + c.seperator + c.totalPages);
}
function setPageSize(table,size) {
var c = table.config;
c.size = size;
c.totalPages = Math.ceil(c.totalRows / c.size);
c.pagerPositionSet = false;
moveToPage(table);
fixPosition(table);
}
function fixPosition(table) {
var c = table.config;
if(!c.pagerPositionSet && c.positionFixed) {
var c = table.config, o = $(table);
if(o.offset) {
c.container.css({
//top: o.offset().top + o.height() + 'px',
//position: 'absolute'
});
}
c.pagerPositionSet = true;
}
}
function moveToFirstPage(table) {
var c = table.config;
c.page = 0;
moveToPage(table);
}
function moveToLastPage(table) {
var c = table.config;
c.page = (c.totalPages-1);
moveToPage(table);
}
function moveToNextPage(table) {
var c = table.config;
c.page++;
if(c.page >= (c.totalPages-1)) {
c.page = (c.totalPages-1);
}
moveToPage(table);
}
function moveToPrevPage(table) {
var c = table.config;
c.page--;
if(c.page <= 0) {
c.page = 0;
}
moveToPage(table);
}
function moveToPage(table) {
var c = table.config;
if(c.page < 0 || c.page > (c.totalPages-1)) {
c.page = 0;
}
renderTable(table,c.rowsCopy);
}
function renderTable(table,rows) {
var c = table.config;
var l = rows.length;
var s = (c.page * c.size);
var e = (s + c.size);
if(e > rows.length ) {
e = rows.length;
}
var tableBody = $(table.tBodies[0]);
// clear the table body
$.tablesorter.clearTableBody(table);
for(var i = s; i < e; i++) {
//tableBody.append(rows[i]);
var o = rows[i];
var l = o.length;
for(var j=0; j < l; j++) {
tableBody[0].appendChild(o[j]);
}
}
fixPosition(table,tableBody);
$(table).trigger("applyWidgets");
if( c.page >= c.totalPages ) {
moveToLastPage(table);
}
updatePageDisplay(c);
}
this.appender = function(table,rows) {
var c = table.config;
c.rowsCopy = rows;
c.totalRows = rows.length;
c.totalPages = Math.ceil(c.totalRows / c.size);
renderTable(table,rows);
};
this.defaults = {
size: 10,
offset: 0,
page: 0,
totalRows: 0,
totalPages: 0,
container: null,
cssNext: '.next',
cssPrev: '.prev',
cssFirst: '.first',
cssLast: '.last',
cssPageDisplay: '.pagedisplay',
cssPageSize: '.pagesize',
seperator: "/",
positionFixed: true,
appender: this.appender
};
this.construct = function(settings) {
return this.each(function() {
config = $.extend(this.config, $.tablesorterPager.defaults, settings);
var table = this, pager = config.container;
$(this).trigger("appendCache");
config.size = parseInt($(".pagesize",pager).val());
$(config.cssFirst,pager).click(function() {
moveToFirstPage(table);
return false;
});
$(config.cssNext,pager).click(function() {
moveToNextPage(table);
return false;
});
$(config.cssPrev,pager).click(function() {
moveToPrevPage(table);
return false;
});
$(config.cssLast,pager).click(function() {
moveToLastPage(table);
return false;
});
$(config.cssPageSize,pager).change(function() {
setPageSize(table,parseInt($(this).val()));
return false;
});
});
};
}
});
// extend plugin scope
$.fn.extend({
tablesorterPager: $.tablesorterPager.construct
});
})(jQuery); | JavaScript |
// JavaScript Document
/**
* @class DecimalFormat
* @constructor
* @param {String} formatStr
* @author Oskan Savli
*/
function DecimalFormat(formatStr)
{
/**
* @fieldOf DecimalFormat
* @type String
*/
this.prefix = '';
/**
* @fieldOf DecimalFormat
* @type String
*/
this.suffix = '';
/**
* @description Grouping size
* @fieldOf DecimalFormat
* @type String
*/
this.comma = 0;
/**
* @description Minimum integer digits to be displayed
* @fieldOf DecimalFormat
* @type Number
*/
this.minInt = 1;
/**
* @description Minimum fractional digits to be displayed
* @fieldOf DecimalFormat
* @type String
*/
this.minFrac = 0;
/**
* @description Maximum fractional digits to be displayed
* @fieldOf DecimalFormat
* @type String
*/
this.maxFrac = 0;
// get prefix
for (var i=0; i<formatStr.length; i++) {
if (formatStr.charAt(i) == '#' || formatStr.charAt(i) == '0') {
this.prefix = formatStr.substring(0,i);
formatStr = formatStr.substring(i);
break;
}
}
// get suffix
this.suffix = formatStr.replace(/[#]|[0]|[,]|[.]/g , '');
// get number as string
var numberStr = formatStr.replace(/[^0#,.]/g , '');
var intStr = '';
var fracStr = '';
var point = numberStr.indexOf('.');
if (point != -1) {
intStr = numberStr.substring(0,point);
fracStr = numberStr.substring(point+1);
}
else {
intStr = numberStr;
}
var commaPos = intStr.lastIndexOf(',');
if (commaPos != -1) {
this.comma = intStr.length - 1 - commaPos;
}
intStr = intStr.replace(/[,]/g , ''); // remove commas
fracStr = fracStr.replace(/[,]|[.]+/g , '');
this.maxFrac = fracStr.length;
var tmp = intStr.replace(/[^0]/g , ''); // remove all except zero
if (tmp.length > this.minInt)
this.minInt = tmp.length;
tmp = fracStr.replace(/[^0]/g , '');
this.minFrac = tmp.length;
}
/**
* @description Formats given value
* @methodOf DecimalFormat
* @param {String} numberStr
* @return {String} Formatted number
* @author Oskan Savli
*/
DecimalFormat.prototype.format = function(numStr) { // 1223.06 --> $1,223.06
// remove prefix, suffix and commas
var numberStr = this.formatBack(numStr).toLowerCase();
// do not format if not a number
if (isNaN(numberStr) || numberStr.length == 0)
return numStr;
//scientific numbers
if (i = numberStr.indexOf("e") != -1) {
var n = Number(numberStr);
if (n=="Infinity" || n=="-Infinity") return numberStr;
numberStr = n+"";
if(numberStr.indexOf('e') != -1) return numberStr;
}
var negative = false;
// remove sign
if (numberStr.charAt(0) == '-') {
negative = true;
numberStr = numberStr.substring(1);
}
else if (numberStr.charAt(0) == '+') {
numberStr = numberStr.substring(1);
}
var point = numberStr.indexOf('.'); // position of point character
var intStr = '';
var fracStr = '';
if (point != -1) {
intStr = numberStr.substring(0,point);
fracStr = numberStr.substring(point+1);
}
else {
intStr = numberStr;
}
fracStr = fracStr.replace(/[.]/ , ''); // remove other point characters
var isPercentage = this.suffix && this.suffix.charAt(0) === '%';
// if percentage, number will be multiplied by 100.
var minInt = this.minInt, minFrac = this.minFrac, maxFrac = this.maxFrac;
if (isPercentage) {
minInt -= 2;
minFrac += 2;
maxFrac += 2;
}
if (fracStr.length > maxFrac) { // round
//case 6143
var num = new Number('0.' + fracStr);
num = (maxFrac == 0)? Math.round(num) : num.toFixed(maxFrac);
// toFixed method has bugs on IE (0.7 --> 0)
fracStr = num.toString(10).substr(2);
var c = (num>=1)? 1:0; //carry
var x, i=intStr.length-1;
while (c) { //increment intStr
if (i==-1) {
intStr = '1'+intStr;
break;
}
else {
x = intStr.charAt(i);
if (x==9) {x='0'; c=1;}
else {x = (++x)+''; c=0;}
intStr = intStr.substring(0,i) + x + intStr.substring(i+1,intStr.length);
i--;
}
}
}
for (var i=fracStr.length; i<minFrac; i++) { // if minFrac=4 then 1.12 --> 1.1200
fracStr = fracStr + '0';
}
while (fracStr.length > minFrac && fracStr.charAt(fracStr.length-1) == '0') { // if minInt=4 then 00034 --> 0034)
fracStr = fracStr.substring(0,fracStr.length-1);
}
for (var i=intStr.length; i<minInt; i++) { // if minInt=4 then 034 --> 0034
intStr = '0' + intStr;
}
while (intStr.length > minInt && intStr.charAt(0) == '0') { // if minInt=4 then 00034 --> 0034)
intStr = intStr.substring(1);
}
if (isPercentage) { // multiply by 100
intStr += fracStr.substring(0,2);
fracStr = fracStr.substring(2);
}
var j = 0;
for(var i=intStr.length; i>0; i--) { // add commas
if (j != 0 && j%this.comma == 0) {
intStr = intStr.substring(0,i) + ',' + intStr.substring(i);
j = 0;
}
j++;
}
var formattedValue;
if (fracStr.length > 0)
formattedValue = this.prefix + intStr + '.' + fracStr + this.suffix;
else
formattedValue = this.prefix + intStr + this.suffix;
if (negative) {
formattedValue = '-' + formattedValue;
}
return formattedValue;
}
/**
* @description Converts formatted value back to non-formatted value
* @methodOf DecimalFormat
* @param {String} fNumberStr Formatted number
* @return {String} Original number
* @author Oskan Savli
*/
DecimalFormat.prototype.formatBack = function(fNumStr) { // $1,223.06 --> 1223.06
fNumStr += ''; //ensure it is string
if (!fNumStr) return ''; //do not return undefined or null
if (!isNaN(fNumStr)) return this.getNumericString(fNumStr);
var fNumberStr = fNumStr;
var negative = false;
if (fNumStr.charAt(0) == '-') {
fNumberStr = fNumberStr.substr(1);
negative = true;
}
var pIndex = fNumberStr.indexOf(this.prefix);
var sIndex = (this.suffix == '')? fNumberStr.length : fNumberStr.indexOf(this.suffix, this.prefix.length+1);
if (pIndex == 0 && sIndex > 0) {
// remove suffix
fNumberStr = fNumberStr.substr(0,sIndex);
// remove prefix
fNumberStr = fNumberStr.substr(this.prefix.length);
// remove commas
fNumberStr = fNumberStr.replace(/,/g , '');
if (negative)
fNumberStr = '-' + fNumberStr;
if (!isNaN(fNumberStr))
return this.getNumericString(fNumberStr);
}
return fNumStr;
}
/**
* @description We shouldn't return strings like 1.000 in formatBack method.
* However, using only Number(str) is not enough, because it omits . in big numbers
* like 23423423423342234.34 => 23423423423342236 . There's a conflict in cases
* 6143 and 6541.
* @methodOf DecimalFormat
* @param {String} str Numberic string
* @return {String} Corrected numeric string
* @author Serdar Bicer
*/
DecimalFormat.prototype.getNumericString = function(str){
//first convert to number
var num = new Number(str);
//check if there is a missing dot
var numStr = num + '';
if (str.indexOf('.')>-1 && numStr.indexOf('.')<0){
//check if original string has all zeros after dot or not
for (var i=str.indexOf('.')+1;i<str.length;i++){
//if not, this means we lost precision
if (str.charAt(i) !== '0') return str;
}
return numStr;
}
return str;
} | JavaScript |
/**
* Jquery ready
* some event click, change ,...
*
* @author hungtd <hungtd@vng.com.vn>
*/
function __cfg(c) {
return(cfg && cfg.cfg && cfg.cfg[c]) ? cfg.cfg[c]: false;
}
(jQuery);
jQuery('html').addClass('js');
jQuery(document).ready(function($) {
// disable right click
// $(this).bind("contextmenu", function(e) {
// e.preventDefault();
// });
// go to top
jQuery("#BoxRight").addScrollControl({
initTop : 350,
offsetTop : 350,
animation : false,
offsetToScroll : 0,
offsetLeft : 970,
RelativeID : "MainHome"
});
// new ticker
$('#notes-home-page').newsticker();
// UI select
if (jQuery(".SelectUI").length > 0) {
jQuery(".SelectUI").addSelectUI({
scrollbarWidth: 10 //default is 10
});
}
if (jQuery(".SelectFrom").length > 0) {
jQuery(".SelectFrom").addSelectUI({
scrollbarWidth: 10 //default is 10
});
}
// hide choose children deal
$('body').livequery('click', function(e) {
$('.JsBuyDealShowChildrenDeal').hide();
});
// foverlabel
$('form .JsOverLabel label').overlabel();
// datepicker
$('form .JsDateTime').fdatepicker();
// time picker
$('.JsTimePicker').livequery(function() {
$(this).timePicker();
});
// parent load ajax
$('.JsRequest a').livequery('click', function() {
$this = $(this);
var aurl = $this.attr('href');
$('.JsResponse').load(aurl);
return false;
});
// a load ajax
$('a.aAjax').livequery('click', function() {
$this = $(this);
var aurl = $this.attr('href');
$('.JsResponse').load(aurl);
return false;
});
// show tab
$('.JsTabA li a').livequery('click', function() {
$this = $(this);
$('.JsTabA li').removeClass('Active');
$this.parent().addClass('Active');
});
// quick login
$('.JsQuickLogin').livequery('click', function() {showFormQuickLogin();});
// count down
$('.js-deal-end-countdown, .js-deal-end-countdown-2').livequery(function() {
//var end_date = parseInt($(this).parents().find('.js-time').html());
var end_date = $(this).parents().find('.js-time').html();
$(this).countdown( {
until: strToOjectDate(end_date),
format: 'H M S'
});
});
// charge
$('.quick-payment-submit').livequery('click', function () {
return ChargeCard();
});
// charge IB
$('#ZingTransactionAmount').livequery('keyup', function()
{
$('#ZingTransactionAmount').val(formatCurrency( $('#ZingTransactionAmount').val()));
// get amount int
var amount = parseInt($('#ZingTransactionAmount').val().replace(/\$|\,/g,''));
// get config promotion
var discount_percent = parseInt($('#promotion-ib-discountpercent').val());
var min_amount = parseInt($('#promotion-ib-minamount').val());
// check not promotion
if (discount_percent < 0 || amount < min_amount) {
$('#ib-discount-amount').html('0');
$('#ib-discounted-amount').html(formatCurrency($('#ZingTransactionAmount').val()));
$('#ib-pay-amount').html(formatCurrency($('#ZingTransactionAmount').val()));
} else {
var discount_amount = (amount * discount_percent) / 100;
var discounted_amount = amount - discount_amount;
$('#ib-discount-amount').html(formatCurrency(discount_amount));
$('#ib-discounted-amount').html(formatCurrency(discounted_amount));
}
});
// submit click IB
$('.js-submit-button-banking').livequery('click', function()
{
if (!checkIB()) {
return false;
}
});
// user Buy
// check amount when user change quantity
$('.js-quantity li').livequery('click', function() {
var new_amount = parseFloat(parseInt($(this).attr('value')) * parseFloat($('#DealDealAmount').val()));
new_amount = isNaN(new_amount) ? 0: new_amount;
/* HUNGTD format currency */
var zingdeal_format_currency = formatCurrency(new_amount);
$('.js-deal-total').html(zingdeal_format_currency);
$('.DealBuyQuantityPopup').html($(this).attr('value'));
$('.DealBuyTotalAmountPoupup').html(zingdeal_format_currency);
if ($('#DealPaymentTypeId6:checked').val() == 6) {
CODConfirm();
}
return false;
});
// change payment method to COD
$('#DealPaymentTypeIdTmp6').livequery('click', function () {
$('#DealPaymentTypeId6').attr('checked', true);
$('.TabOption li').removeClass('Active');
$(this).parent().parent().addClass('Active');
CODConfirm();
});
// set default
if ($('#DealPaymentTypeId4').val() == 4) {
$('#DealPaymentTypeId4').attr('checked', true);
$('#DealPaymentTypeIdTmp4').attr('checked', true);
} else if ($('#DealPaymentTypeId6').val() == 6) {
$('#DealPaymentTypeId6').attr('checked', true);
$('#DealPaymentTypeIdTmp6').attr('checked', true);
CODConfirm();
}
$('#DealQuantity').val(1);
// change payment method to Zing Xu
$('#DealPaymentTypeIdTmp4').livequery('click', function () {
$('#DealPaymentTypeId4').attr('checked', true);
$('.TabOption li').removeClass('Active');
$(this).parent().parent().addClass('Active');
ShowHideDiv('.JsZingXuMethod', '.JsCODMethod');
$('.JsCODMethod').children().remove();
});
// user click buy
$('.js-buy-confirm').livequery('click', function () {
// check xem user da login hay chua.
// neu user chua login hien popup login nhanh
if(isUserLogin()) {
if ($('#DealPaymentTypeId6:checked').val() == 6) {
if (checkCODAddress() == 1) {
var is_confirm_cod = $('#isConfirmCOD').val();
if (is_confirm_cod == 1) {
var aurlpopup = __cfg('path_relative') + 'delivery_addresses/popup_confirm'+'/cache:'+Math.floor(Math.random()*10000);
PopUpZD(aurlpopup, 1);
} else {
//AddDeliveryAddressNotConfirm();
PopUpZD($('.AlertBuyDealCOD').html(), 0);
}
}
} else if ($('#DealPaymentTypeId4:checked').val() == 4) {
if ($('#DealIsGift').val() == 1) {
$('.DealBuyQuantityPopup').html($('#JsBuyGiftFriendQuantity').val());
var giftQuantity = parseInt($('.DealBuyQuantityPopup').html());
var giftAmount = giftQuantity*parseFloat($('#DealDealAmount').val());
$('.DealBuyTotalAmountPoupup').html(giftQuantity);
$('.DealBuyTotalAmountPoupup').html(formatCurrency(giftAmount));
}
if (parseInt($('.DealBuyQuantityPopup').html()) > 0)
PopUpZD($('.AlertBuyDealZingXu').html(), 0);
else
AlertZingDeal(JsLangZD.alert_choose_quantity);
}
} else {
showFormQuickLogin();
}
return false;
});
// user view buy gift for friend
$('#JsBuyGiftAddFriend').livequery('click', function() {
// check data
if (checkGiftForm() == false) return false;
// get data input
var giftFrom = $('input[name=Jsgift_from]').val();
var giftQuantity = $('select[name=Jsquantity]').val();
var giftTo = $('input[name=Jsgift_to]').val();
var giftMail = $('input[name=Jsgift_mail]').val();
var giftPhone = $('input[name=Jsgift_phone]').val();
var giftMessage = $('textarea[name=Jsmessage]').val();
var dataInput = giftFrom + '|' + giftQuantity + '|' + giftTo + '|' + giftMail + '|' + giftPhone + '|' + giftMessage;
// add friend count
var cQuantity = parseInt($('#JsBuyGiftFriendQuantity').val());
var addQuantity = cQuantity + parseInt(giftQuantity);
var maxQuantity = parseInt($('#max_info_number').val());
// check quantity
if (addQuantity <= maxQuantity) {
$('#JsBuyGiftFriendQuantity').val(addQuantity);
} else {
return false;
}
// add item to cart
// get quanti ty
var quantity = parseInt($('select[name=Jsquantity]').val());
// get price item
var sPrice = $('.Box-VoucherMain .TitleVoucher .Box-Voucher .Voucher .cr').html();
var dPrice = parseFloat(sPrice.toString().replace(/\$|\,/g,''));
var tdPrice = (dPrice * quantity);
var tPrice = formatCurrency(tdPrice);
// get current totla price
var sShowPrice = $('.js-deal-total').html();
var dShowPrice = parseFloat(sShowPrice.toString().replace(/\$|\,/g,''));
var showPrice = tdPrice + dShowPrice;
// html row
var rowCart = '<tr class="OddRow OddRowViDeal">';
rowCart += '<td class=" VeztTop">' + $('.Box-VoucherMain .TitleVoucher p').html() + '</td>';
rowCart += '<td class="HorzCenter VeztTop JsBuyGiftRowQuantity">' + quantity + '</td>';
rowCart += '<td class="HorzCenter VeztTop">' + sPrice + '</td>';
rowCart += '<td class="HorzCenter VeztTop JsBuyGiftRowtPrice">' + tPrice + '</td>';
rowCart += '<td class="HorzCenter VeztTop"><a href="javascript:void(0)" class="JsBuyGiftDelRow"> </a></td>';
rowCart += '<td class="hide"><textarea name="buy_gift_info_friend[]" class="hide">' + dataInput + '</textarea></td></tr>';
$('#JsBuyGiftCart').append(rowCart);
// add current price
$('.js-deal-total').html(formatCurrency(showPrice));
});
// remove friend in buy gift
$('a.JsBuyGiftDelRow').livequery('click', function () {
var dQuantity = $(this).parent().parent().children('.JsBuyGiftRowQuantity').html();
var cQuantity = parseInt($('#JsBuyGiftFriendQuantity').val());
var addQuantity = cQuantity - parseInt(dQuantity);
$('#JsBuyGiftFriendQuantity').val(addQuantity);
// remove
$(this).parent().parent().remove();
// get current price
// get this row price
var sRowPrice = $(this).parent().parent().children('.JsBuyGiftRowtPrice').html();
var dRowPrice = parseFloat(sRowPrice.toString().replace(/\$|\,/g,''));
// get current totla price
var sShowPrice = $('.js-deal-total').html();
var dShowPrice = parseFloat(sShowPrice.toString().replace(/\$|\,/g,''));
var showPrice = dShowPrice - dRowPrice;
// add current price
$('.js-deal-total').html(formatCurrency(showPrice));
});
// User Show Menu
$('.JsUserMenu').livequery('click', function () {
$('.userMenuRight').slideToggle();
});
// Search Transaction
$('.JsTransactionSb').livequery('click', function () {
var ride = $('input[name=rediosearchtmp]:checked').val();
if (ride == 'day') {
location.replace($('#ztartday').val());
} else if (ride == 'week') {
location.replace($('#ztartweek').val());
} else if (ride == 'month') {
location.replace($('#ztartmonth').val());
} else if (ride == 'all') {
$('#ZingTransactionIndexForm').submit();
}
});
// check balance Zing
if ($('span').hasClass('JsBalance') == true) {getBalanceZing();}
// remove iframe
$('#IfSSOLogin').contents().find('head').html('<title></title>');
$('#IfSSOLogin').contents().find('body').html('<div></div>');
// hide popup
$('.JsCancel').livequery('click', function() {
AlertHide();
});
// show hide topic
$('a.AnsView2').livequery('click', function() {
$(this).hide();
$(this).siblings('.AnsView1').show();
});
$('a.AnsView1').livequery('click', function() {
$(this).hide();
$(this).siblings('.AnsView2').show();
$(this).parents('.BoxView1').children('.JsTopicContent').hide();
$(this).parents('.BoxView2').children('.JsTopicContent').hide();
});
// kiem tra tai khoan tren Zing Deal
$('.JsCheckZingDealAccount').livequery('click', function() {
$this = $(this);
var inputUsername = $(this).siblings('input');
checkAccountZingDeal(inputUsername);
});
// kiem tra tai khoan tren Zing ID
$('.JsCheckZingIDAccount').livequery('click', function() {
$this = $(this);
var inputUsername = $(this).siblings('input');
checkAccountZingID(inputUsername);
});
// reload captcha
$('#contacts-add form a.js-captcha-reload, #users-register form a.js-captcha-reload').livequery('click', function() {
captcha_img_src = $(this).parents('.js-captcha-container').find('.captcha-img').attr('src');
captcha_img_src = captcha_img_src.substring(0, captcha_img_src.lastIndexOf('/'));
$(this).parents('.js-captcha-container').find('.captcha-img').attr('src', captcha_img_src + '/' + Math.random());
if ($('.js-captcha-input')) {
$('.js-captcha-input').val('');
}
return false;
});
// check length password
$('.JsPassword').livequery('keyup', function() {
$this = $(this);
// get pwd
var pwd = $this.val();
// kiem tra pwd
// kiem tra pass co chu so hay khong
re = /[0-9]/;
if(!re.test(pwd)) chu_so = 0; else chu_so = 1;
// kiem tra pass co chu thuong hay khong
re = /[a-z]/;
if(!re.test(pwd)) chu_thuong = 0; else chu_thuong = 1;
// kiem tra pass co chu hoa hay khong
re = /[A-Z]/;
if(!re.test(pwd)) chu_hoa = 0; else chu_hoa = 1;
// kiem tra pass cho ky tu dac biet hay khong
re = /[\W_]/;
if(!re.test(pwd)) ky_tu = 0; else ky_tu = 1;
// total conditions
tCondition = parseInt(chu_so) + parseInt(chu_thuong) + parseInt(chu_hoa) + parseInt(ky_tu);
if (pwd.length >= 8 && tCondition >= 0) $('#meta1').addClass('meta'); else $('#meta1').removeClass('meta');
if (pwd.length >= 8 && tCondition >= 2) $('#meta2').addClass('meta'); else $('#meta2').removeClass('meta');
if (pwd.length >= 8 && tCondition >= 3) $('#meta3').addClass('meta'); else $('#meta3').removeClass('meta');
if (pwd.length >= 8 && tCondition >= 4) $('#meta4').addClass('meta'); else $('#meta4').removeClass('meta');
});
// check pwd again
$('.JsConfirmPassword').livequery('blur', function() {
$this = $(this);
if ($this.val() == $('.JsPassword').val()) $this.siblings('.Note').hide();
else $this.siblings('.Note').show();
});
// check email
$('.JsEmail').livequery('blur', function() {
$this = $(this);
if ($this.siblings('.Note').hasClass('empty')) if ($this.val() == '') return true;
if (validateEmail($this.val())) $this.siblings('.Note').hide();
else $this.siblings('.Note').show();
});
// check phone
$('.JsPhone').livequery('blur', function() {
$this = $(this);
if ($this.siblings('.Note').hasClass('empty')) if ($this.val() == '') return true;
if (validatePhone($this.val())) $this.siblings('.Note').hide();
else $this.siblings('.Note').show();
});
// check empty
$('.JsEmpty').livequery('blur', function() {
$this = $(this);
if ($this.val()) $this.siblings('.Note').hide();
else $this.siblings('.Note').show();
});
// show label deal category
$('.JsDealCategoryTop ul li').livequery('mouseover', function() {
$('.JsDealCategoryTop ul li a').show();
$('.JsDealCategoryTop').removeClass('dc-nav-small');$('.JsDealCategoryTop').addClass('dc-nav-big');
});
// hide label deal category
$('.JsDealCategoryTop ul li').livequery('mouseout', function() {
$('.JsDealCategoryTop ul li a.DCLabel').hide();
$('.JsDealCategoryTop').removeClass('dc-nav-big');$('.JsDealCategoryTop').addClass('dc-nav-small');
});
// change deal category when (window) resize small
$(window).resize(function() {
$this = $(this);
if ($this.width() <= 1100) $('.JsDealCategoryTop').addClass('dc-nav-slow');
else $('.JsDealCategoryTop').removeClass('dc-nav-slow');
});
// change deal category when (window) small
if ($(window).width() <= 1100) $('.JsDealCategoryTop').addClass('dc-nav-slow');
else $('.JsDealCategoryTop').removeClass('dc-nav-slow');
// recent deal searcj
$('.JsRecentDealSearch').livequery('click', function() {
var keyWord = $('#RecentDealSearchForm input[name=rdkeyword]').val();
keyWord = encodeURI(keyWord);
var from_date = $('#RecentDealSearchForm input[name=rdsdate_text]').val();
var to_date = $('#RecentDealSearchForm input[name=rdtdate_text]').val();
var ftimeSearch = toTimestamp(from_date);
var ttimeSearch = toTimestamp(to_date);
var categoryid = $('#RecentDealSearchForm select[name=rdcategoryid]').val();
var RURL = $('#RecentDealSearchForm input[name=URL_FormSearch]').val();
var RSURL = (RURL + '/q:' + keyWord + '/sdate:' + ftimeSearch + '/edate:' + ttimeSearch + '/category:' + categoryid);
window.location.href = RSURL;
});
// show quick instruction
$('.JsTitleQuickIntruction').livequery('click', function() {
$this = $(this);
if ($this.parent().hasClass('show')) {
$('ul.Huongdan li').removeClass('show');
$('p.JsQuickIntruction').hide();
} else {
$('ul.Huongdan li').removeClass('show');
$this.parent().addClass('show');
$('p.JsQuickIntruction').hide();
$this.siblings('p.JsQuickIntruction').show();
}
});
// auto submit
$('form select.js-admin-index-autosubmit').livequery('change', function() {
if ($('.js-checkbox-list:checked').val() != 1 && $(this).val() >= 1) {
alert('Please select atleast one record!');
$(this).val('');
return false;
} else if ($(this).val() >= 1) {
if (window.confirm('Bạn có chắc là thực hiện hành động này này?')) {
$(this).parents('form').submit();
} else {
$(this).val('');
}
}
});
// choose City
//$('#DealCitySelect').livequery('change', function () {
//window.location.href = $(this).val();
//});
// change select to city defalt
var ZDCITY = readCookie('CakeCookie[city_slug]');
var JsCurrentCity = $('.'+ZDCITY).html();
$('#province .DropListUI p').html(JsCurrentCity);
//$('.'+ZDCITY).attr('selected', 'selected');
$('.SelectFrom li').livequery('click', function() {
window.location.href = $('#DealCitySelect').val();
});
// count deal user when deal is hot deal
if ($('strong').hasClass('JsQuantityDealUserCount')) {
var aurl=__cfg('path_relative')+'ajaxpages/deal_countbought/'+$('#JsDealViewDealId').html()+'/cache:'+Math.floor(Math.random()*10000);
$('.JsQuantityDealUserCount').load(aurl);
}
// show list subdeal
$('.JsShowChildrenDeal').livequery('click', function(e) {
$this = $(this);
var is_gift;
if ($this.hasClass('JsDealBuyGift')) {is_gift = 1;} else {is_gift = 0}
var dealID = $this.siblings('.JsDealId').html();
var aurl=__cfg('path_relative')+'ajaxpages/show_childrendeal/'+dealID+'/'+is_gift+'/1'+'/cache:'+Math.floor(Math.random()*10000);
PopUpZD(aurl, 1);
e.preventDefault();
return false;
});
// show choose other children deal
$('.JsBuyDealShowChooseDeal').livequery('click', function(e) {
var deal_id = $('input[name=JsBuyDealId]').val();
chooseOtherChildrenDeal(deal_id);
e.stopPropagation();
});
// tip for sub deal
$('a.fixedTip').livequery(function(){
var tip = $(this).siblings('.JsTooltipContent').html();
$(this).aToolTip({
fixed: false,
xOffset: 10,
yOffset: -80,
tipContent: tip
});
});
// get ward for COD
$('#DADistrictId').livequery('change', function() {
$this = $(this);
var aurl = __cfg('path_relative')+'district_wards/index/' + $this.val() + '/cache:'+Math.floor(Math.random()*10000);
$('#DAWard').load(aurl);
});
});
// end jQuery
if (getCookie('ice') == '') {
document.cookie = 'ice=true;path=/';
} | JavaScript |
/**
* Jquery ready
* some event click, change ,...
*
* @author hungtd <hungtd@vng.com.vn>
*/
function __cfg(c) {
return(cfg && cfg.cfg && cfg.cfg[c]) ? cfg.cfg[c]: false;
}
(jQuery);
jQuery('html').addClass('js');
jQuery(document).ready(function($) {
// disable right click
// $(this).bind("contextmenu", function(e) {
// e.preventDefault();
// });
// go to top
jQuery("#BoxRight").addScrollControl({
initTop : 350,
offsetTop : 350,
animation : false,
offsetToScroll : 0,
offsetLeft : 970,
RelativeID : "MainHome"
});
// new ticker
$('#notes-home-page').newsticker();
// UI select
if (jQuery(".SelectUI").length > 0) {
jQuery(".SelectUI").addSelectUI({
scrollbarWidth: 10 //default is 10
});
}
if (jQuery(".SelectFrom").length > 0) {
jQuery(".SelectFrom").addSelectUI({
scrollbarWidth: 10 //default is 10
});
}
// hide choose children deal
$('body').livequery('click', function(e) {
$('.JsBuyDealShowChildrenDeal').hide();
});
// foverlabel
$('form .JsOverLabel label').overlabel();
// datepicker
$('form .JsDateTime').fdatepicker();
// time picker
$('.JsTimePicker').livequery(function() {
$(this).timePicker();
});
// parent load ajax
$('.JsRequest a').livequery('click', function() {
$this = $(this);
var aurl = $this.attr('href');
$('.JsResponse').load(aurl);
return false;
});
// a load ajax
$('a.aAjax').livequery('click', function() {
$this = $(this);
var aurl = $this.attr('href');
$('.JsResponse').load(aurl);
return false;
});
// show tab
$('.JsTabA li a').livequery('click', function() {
$this = $(this);
$('.JsTabA li').removeClass('Active');
$this.parent().addClass('Active');
});
// quick login
$('.JsQuickLogin').livequery('click', function() {showFormQuickLogin();});
// count down
$('.js-deal-end-countdown, .js-deal-end-countdown-2').livequery(function() {
//var end_date = parseInt($(this).parents().find('.js-time').html());
var end_date = $(this).parents().find('.js-time').html();
$(this).countdown( {
until: strToOjectDate(end_date),
format: 'H M S'
});
});
// charge
$('.quick-payment-submit').livequery('click', function () {
return ChargeCard();
});
// charge IB
$('#ZingTransactionAmount').livequery('keyup', function()
{
$('#ZingTransactionAmount').val(formatCurrency( $('#ZingTransactionAmount').val()));
// get amount int
var amount = parseInt($('#ZingTransactionAmount').val().replace(/\$|\,/g,''));
// get config promotion
var discount_percent = parseInt($('#promotion-ib-discountpercent').val());
var min_amount = parseInt($('#promotion-ib-minamount').val());
// check not promotion
if (discount_percent < 0 || amount < min_amount) {
$('#ib-discount-amount').html('0');
$('#ib-discounted-amount').html(formatCurrency($('#ZingTransactionAmount').val()));
$('#ib-pay-amount').html(formatCurrency($('#ZingTransactionAmount').val()));
} else {
var discount_amount = (amount * discount_percent) / 100;
var discounted_amount = amount - discount_amount;
$('#ib-discount-amount').html(formatCurrency(discount_amount));
$('#ib-discounted-amount').html(formatCurrency(discounted_amount));
}
});
// submit click IB
$('.js-submit-button-banking').livequery('click', function()
{
if (!checkIB()) {
return false;
}
});
// user Buy
// check amount when user change quantity
$('.js-quantity li').livequery('click', function() {
var new_amount = parseFloat(parseInt($(this).attr('value')) * parseFloat($('#DealDealAmount').val()));
new_amount = isNaN(new_amount) ? 0: new_amount;
/* HUNGTD format currency */
var zingdeal_format_currency = formatCurrency(new_amount);
$('.js-deal-total').html(zingdeal_format_currency);
$('.DealBuyQuantityPopup').html($(this).attr('value'));
$('.DealBuyTotalAmountPoupup').html(zingdeal_format_currency);
if ($('#DealPaymentTypeId6:checked').val() == 6) {
CODConfirm();
}
return false;
});
// change payment method to COD
$('#DealPaymentTypeIdTmp6').livequery('click', function () {
$('#DealPaymentTypeId6').attr('checked', true);
$('.TabOption li').removeClass('Active');
$(this).parent().parent().addClass('Active');
CODConfirm();
});
// set default
if ($('#DealPaymentTypeId4').val() == 4) {
$('#DealPaymentTypeId4').attr('checked', true);
$('#DealPaymentTypeIdTmp4').attr('checked', true);
} else if ($('#DealPaymentTypeId6').val() == 6) {
$('#DealPaymentTypeId6').attr('checked', true);
$('#DealPaymentTypeIdTmp6').attr('checked', true);
CODConfirm();
}
$('#DealQuantity').val(1);
// change payment method to Zing Xu
$('#DealPaymentTypeIdTmp4').livequery('click', function () {
$('#DealPaymentTypeId4').attr('checked', true);
$('.TabOption li').removeClass('Active');
$(this).parent().parent().addClass('Active');
ShowHideDiv('.JsZingXuMethod', '.JsCODMethod');
$('.JsCODMethod').children().remove();
});
// user click buy
$('.js-buy-confirm').livequery('click', function () {
// check xem user da login hay chua.
// neu user chua login hien popup login nhanh
if(isUserLogin()) {
if ($('#DealPaymentTypeId6:checked').val() == 6) {
if (checkCODAddress() == 1) {
var is_confirm_cod = $('#isConfirmCOD').val();
if (is_confirm_cod == 1) {
var aurlpopup = __cfg('path_relative') + 'delivery_addresses/popup_confirm'+'/cache:'+Math.floor(Math.random()*10000);
PopUpZD(aurlpopup, 1);
} else {
//AddDeliveryAddressNotConfirm();
PopUpZD($('.AlertBuyDealCOD').html(), 0);
}
}
} else if ($('#DealPaymentTypeId4:checked').val() == 4) {
if ($('#DealIsGift').val() == 1) {
$('.DealBuyQuantityPopup').html($('#JsBuyGiftFriendQuantity').val());
var giftQuantity = parseInt($('.DealBuyQuantityPopup').html());
var giftAmount = giftQuantity*parseFloat($('#DealDealAmount').val());
$('.DealBuyTotalAmountPoupup').html(giftQuantity);
$('.DealBuyTotalAmountPoupup').html(formatCurrency(giftAmount));
}
if (parseInt($('.DealBuyQuantityPopup').html()) > 0)
PopUpZD($('.AlertBuyDealZingXu').html(), 0);
else
AlertZingDeal(JsLangZD.alert_choose_quantity);
}
} else {
showFormQuickLogin();
}
return false;
});
// user view buy gift for friend
$('#JsBuyGiftAddFriend').livequery('click', function() {
// check data
if (checkGiftForm() == false) return false;
// get data input
var giftFrom = $('input[name=Jsgift_from]').val();
var giftQuantity = $('select[name=Jsquantity]').val();
var giftTo = $('input[name=Jsgift_to]').val();
var giftMail = $('input[name=Jsgift_mail]').val();
var giftPhone = $('input[name=Jsgift_phone]').val();
var giftMessage = $('textarea[name=Jsmessage]').val();
var dataInput = giftFrom + '|' + giftQuantity + '|' + giftTo + '|' + giftMail + '|' + giftPhone + '|' + giftMessage;
// add friend count
var cQuantity = parseInt($('#JsBuyGiftFriendQuantity').val());
var addQuantity = cQuantity + parseInt(giftQuantity);
var maxQuantity = parseInt($('#max_info_number').val());
// check quantity
if (addQuantity <= maxQuantity) {
$('#JsBuyGiftFriendQuantity').val(addQuantity);
} else {
return false;
}
// add item to cart
// get quanti ty
var quantity = parseInt($('select[name=Jsquantity]').val());
// get price item
var sPrice = $('.Box-VoucherMain .TitleVoucher .Box-Voucher .Voucher .cr').html();
var dPrice = parseFloat(sPrice.toString().replace(/\$|\,/g,''));
var tdPrice = (dPrice * quantity);
var tPrice = formatCurrency(tdPrice);
// get current totla price
var sShowPrice = $('.js-deal-total').html();
var dShowPrice = parseFloat(sShowPrice.toString().replace(/\$|\,/g,''));
var showPrice = tdPrice + dShowPrice;
// html row
var rowCart = '<tr class="OddRow OddRowViDeal">';
rowCart += '<td class=" VeztTop">' + $('.Box-VoucherMain .TitleVoucher p').html() + '</td>';
rowCart += '<td class="HorzCenter VeztTop JsBuyGiftRowQuantity">' + quantity + '</td>';
rowCart += '<td class="HorzCenter VeztTop">' + sPrice + '</td>';
rowCart += '<td class="HorzCenter VeztTop JsBuyGiftRowtPrice">' + tPrice + '</td>';
rowCart += '<td class="HorzCenter VeztTop"><a href="javascript:void(0)" class="JsBuyGiftDelRow"> </a></td>';
rowCart += '<td class="hide"><textarea name="buy_gift_info_friend[]" class="hide">' + dataInput + '</textarea></td></tr>';
$('#JsBuyGiftCart').append(rowCart);
// add current price
$('.js-deal-total').html(formatCurrency(showPrice));
});
// remove friend in buy gift
$('a.JsBuyGiftDelRow').livequery('click', function () {
var dQuantity = $(this).parent().parent().children('.JsBuyGiftRowQuantity').html();
var cQuantity = parseInt($('#JsBuyGiftFriendQuantity').val());
var addQuantity = cQuantity - parseInt(dQuantity);
$('#JsBuyGiftFriendQuantity').val(addQuantity);
// remove
$(this).parent().parent().remove();
// get current price
// get this row price
var sRowPrice = $(this).parent().parent().children('.JsBuyGiftRowtPrice').html();
var dRowPrice = parseFloat(sRowPrice.toString().replace(/\$|\,/g,''));
// get current totla price
var sShowPrice = $('.js-deal-total').html();
var dShowPrice = parseFloat(sShowPrice.toString().replace(/\$|\,/g,''));
var showPrice = dShowPrice - dRowPrice;
// add current price
$('.js-deal-total').html(formatCurrency(showPrice));
});
// User Show Menu
$('.JsUserMenu').livequery('click', function () {
$('.userMenuRight').slideToggle();
});
// Search Transaction
$('.JsTransactionSb').livequery('click', function () {
var ride = $('input[name=rediosearchtmp]:checked').val();
if (ride == 'day') {
location.replace($('#ztartday').val());
} else if (ride == 'week') {
location.replace($('#ztartweek').val());
} else if (ride == 'month') {
location.replace($('#ztartmonth').val());
} else if (ride == 'all') {
$('#ZingTransactionIndexForm').submit();
}
});
// check balance Zing
if ($('span').hasClass('JsBalance') == true) {getBalanceZing();}
// remove iframe
$('#IfSSOLogin').contents().find('head').html('<title></title>');
$('#IfSSOLogin').contents().find('body').html('<div></div>');
// hide popup
$('.JsCancel').livequery('click', function() {
AlertHide();
});
// show hide topic
$('a.AnsView2').livequery('click', function() {
$(this).hide();
$(this).siblings('.AnsView1').show();
});
$('a.AnsView1').livequery('click', function() {
$(this).hide();
$(this).siblings('.AnsView2').show();
$(this).parents('.BoxView1').children('.JsTopicContent').hide();
$(this).parents('.BoxView2').children('.JsTopicContent').hide();
});
// kiem tra tai khoan tren Zing Deal
$('.JsCheckZingDealAccount').livequery('click', function() {
$this = $(this);
var inputUsername = $(this).siblings('input');
checkAccountZingDeal(inputUsername);
});
// kiem tra tai khoan tren Zing ID
$('.JsCheckZingIDAccount').livequery('click', function() {
$this = $(this);
var inputUsername = $(this).siblings('input');
checkAccountZingID(inputUsername);
});
// reload captcha
$('#contacts-add form a.js-captcha-reload, #users-register form a.js-captcha-reload').livequery('click', function() {
captcha_img_src = $(this).parents('.js-captcha-container').find('.captcha-img').attr('src');
captcha_img_src = captcha_img_src.substring(0, captcha_img_src.lastIndexOf('/'));
$(this).parents('.js-captcha-container').find('.captcha-img').attr('src', captcha_img_src + '/' + Math.random());
if ($('.js-captcha-input')) {
$('.js-captcha-input').val('');
}
return false;
});
// check length password
$('.JsPassword').livequery('keyup', function() {
$this = $(this);
// get pwd
var pwd = $this.val();
// kiem tra pwd
// kiem tra pass co chu so hay khong
re = /[0-9]/;
if(!re.test(pwd)) chu_so = 0; else chu_so = 1;
// kiem tra pass co chu thuong hay khong
re = /[a-z]/;
if(!re.test(pwd)) chu_thuong = 0; else chu_thuong = 1;
// kiem tra pass co chu hoa hay khong
re = /[A-Z]/;
if(!re.test(pwd)) chu_hoa = 0; else chu_hoa = 1;
// kiem tra pass cho ky tu dac biet hay khong
re = /[\W_]/;
if(!re.test(pwd)) ky_tu = 0; else ky_tu = 1;
// total conditions
tCondition = parseInt(chu_so) + parseInt(chu_thuong) + parseInt(chu_hoa) + parseInt(ky_tu);
if (pwd.length >= 8 && tCondition >= 0) $('#meta1').addClass('meta'); else $('#meta1').removeClass('meta');
if (pwd.length >= 8 && tCondition >= 2) $('#meta2').addClass('meta'); else $('#meta2').removeClass('meta');
if (pwd.length >= 8 && tCondition >= 3) $('#meta3').addClass('meta'); else $('#meta3').removeClass('meta');
if (pwd.length >= 8 && tCondition >= 4) $('#meta4').addClass('meta'); else $('#meta4').removeClass('meta');
});
// check pwd again
$('.JsConfirmPassword').livequery('blur', function() {
$this = $(this);
if ($this.val() == $('.JsPassword').val()) $this.siblings('.Note').hide();
else $this.siblings('.Note').show();
});
// check email
$('.JsEmail').livequery('blur', function() {
$this = $(this);
if ($this.siblings('.Note').hasClass('empty')) if ($this.val() == '') return true;
if (validateEmail($this.val())) $this.siblings('.Note').hide();
else $this.siblings('.Note').show();
});
// check phone
$('.JsPhone').livequery('blur', function() {
$this = $(this);
if ($this.siblings('.Note').hasClass('empty')) if ($this.val() == '') return true;
if (validatePhone($this.val())) $this.siblings('.Note').hide();
else $this.siblings('.Note').show();
});
// check empty
$('.JsEmpty').livequery('blur', function() {
$this = $(this);
if ($this.val()) $this.siblings('.Note').hide();
else $this.siblings('.Note').show();
});
// show label deal category
$('.JsDealCategoryTop ul li').livequery('mouseover', function() {
$('.JsDealCategoryTop ul li a').show();
$('.JsDealCategoryTop').removeClass('dc-nav-small');$('.JsDealCategoryTop').addClass('dc-nav-big');
});
// hide label deal category
$('.JsDealCategoryTop ul li').livequery('mouseout', function() {
$('.JsDealCategoryTop ul li a.DCLabel').hide();
$('.JsDealCategoryTop').removeClass('dc-nav-big');$('.JsDealCategoryTop').addClass('dc-nav-small');
});
// change deal category when (window) resize small
$(window).resize(function() {
$this = $(this);
if ($this.width() <= 1100) $('.JsDealCategoryTop').addClass('dc-nav-slow');
else $('.JsDealCategoryTop').removeClass('dc-nav-slow');
});
// change deal category when (window) small
if ($(window).width() <= 1100) $('.JsDealCategoryTop').addClass('dc-nav-slow');
else $('.JsDealCategoryTop').removeClass('dc-nav-slow');
// recent deal searcj
$('.JsRecentDealSearch').livequery('click', function() {
var keyWord = $('#RecentDealSearchForm input[name=rdkeyword]').val();
keyWord = encodeURI(keyWord);
var from_date = $('#RecentDealSearchForm input[name=rdsdate_text]').val();
var to_date = $('#RecentDealSearchForm input[name=rdtdate_text]').val();
var ftimeSearch = toTimestamp(from_date);
var ttimeSearch = toTimestamp(to_date);
var categoryid = $('#RecentDealSearchForm select[name=rdcategoryid]').val();
var RURL = $('#RecentDealSearchForm input[name=URL_FormSearch]').val();
var RSURL = (RURL + '/q:' + keyWord + '/sdate:' + ftimeSearch + '/edate:' + ttimeSearch + '/category:' + categoryid);
window.location.href = RSURL;
});
// show quick instruction
$('.JsTitleQuickIntruction').livequery('click', function() {
$this = $(this);
if ($this.parent().hasClass('show')) {
$('ul.Huongdan li').removeClass('show');
$('p.JsQuickIntruction').hide();
} else {
$('ul.Huongdan li').removeClass('show');
$this.parent().addClass('show');
$('p.JsQuickIntruction').hide();
$this.siblings('p.JsQuickIntruction').show();
}
});
// auto submit
$('form select.js-admin-index-autosubmit').livequery('change', function() {
if ($('.js-checkbox-list:checked').val() != 1 && $(this).val() >= 1) {
alert('Please select atleast one record!');
$(this).val('');
return false;
} else if ($(this).val() >= 1) {
if (window.confirm('Bạn có chắc là thực hiện hành động này này?')) {
$(this).parents('form').submit();
} else {
$(this).val('');
}
}
});
// choose City
//$('#DealCitySelect').livequery('change', function () {
//window.location.href = $(this).val();
//});
// change select to city defalt
var ZDCITY = readCookie('CakeCookie[city_slug]');
var JsCurrentCity = $('.'+ZDCITY).html();
$('#province .DropListUI p').html(JsCurrentCity);
//$('.'+ZDCITY).attr('selected', 'selected');
$('.SelectFrom li').livequery('click', function() {
window.location.href = $('#DealCitySelect').val();
});
// count deal user when deal is hot deal
if ($('strong').hasClass('JsQuantityDealUserCount')) {
var aurl=__cfg('path_relative')+'ajaxpages/deal_countbought/'+$('#JsDealViewDealId').html()+'/cache:'+Math.floor(Math.random()*10000);
$('.JsQuantityDealUserCount').load(aurl);
}
// show list subdeal
$('.JsShowChildrenDeal').livequery('click', function(e) {
$this = $(this);
var is_gift;
if ($this.hasClass('JsDealBuyGift')) {is_gift = 1;} else {is_gift = 0}
var dealID = $this.siblings('.JsDealId').html();
var aurl=__cfg('path_relative')+'ajaxpages/show_childrendeal/'+dealID+'/'+is_gift+'/1'+'/cache:'+Math.floor(Math.random()*10000);
PopUpZD(aurl, 1);
e.preventDefault();
return false;
});
// show choose other children deal
$('.JsBuyDealShowChooseDeal').livequery('click', function(e) {
var deal_id = $('input[name=JsBuyDealId]').val();
chooseOtherChildrenDeal(deal_id);
e.stopPropagation();
});
// tip for sub deal
$('a.fixedTip').livequery(function(){
var tip = $(this).siblings('.JsTooltipContent').html();
$(this).aToolTip({
fixed: false,
xOffset: 10,
yOffset: -80,
tipContent: tip
});
});
// get ward for COD
$('#DADistrictId').livequery('change', function() {
$this = $(this);
var aurl = __cfg('path_relative')+'district_wards/index/' + $this.val() + '/cache:'+Math.floor(Math.random()*10000);
$('#DAWard').load(aurl);
});
});
// end jQuery
if (getCookie('ice') == '') {
document.cookie = 'ice=true;path=/';
} | JavaScript |
/////////// Xu ly huy bo //////////////
var ref = document.referrer;
/////////////////
function huybo_ref(productID){
if(ref.indexOf('account') != -1){
window.location='/account/index.'+productID+'.html';
}else{
window.location='/home/index.'+productID+'.html';
}
}
////////////////////
var UserName_Error = new Array(
'Tên đăng nhập này không tồn tại, vui lòng kiểm tra lại.'
);
var Password_Error = new Array(
'Không được nhập tiếng việt có dấu.',
'Phải có ít nhất 4 ký tự.',
'Phải có ít nhất 6 ký tự.',
'Xác nhận mật khẩu phải giống mật khẩu.',
'Xác nhận mã game phải giống mã game.',
'Mã game không được trùng với Mật khẩu.',
'Mật khẩu mới và mật khẩu cũ không được trùng nhau.',
'Mật khẩu không được trùng với mã game.'
);
var Require_Error ='Bạn phải nhập thông tin này.';
var Verify_Error = new Array(
'Mã xác nhận hình ảnh không đúng.',
'Mã xác nhận hình ảnh không đúng.'
);
var Answer_Error = 'Bạn chưa nhập câu trả lời';
var Persional_Error = new Array(
'Phải có từ 8-15 ký tự.',
'Ngày cấp không hợp lệ.',
'Ngày sinh không hợp lệ.'
);
var Email_Error =new Array(
'Địa chỉ email không hợp lệ.'
);
var Question_Error = new Array(
'Bạn chưa chọn câu hỏi.'
);
var Region_Error = new Array(
'Bạn chưa chọn nơi cấp.'
);
var Profile_Error = new Array(
'Họ Tên phải có ít nhất 2 từ.',
'Ngày sinh không hợp lệ.',
'Bạn chưa chọn giới tính.'
);
function show_error(input,err){
$('#'+input+'_tr').addClass('tr_error');
$('#'+input+'_error').html(err);
$('#'+input+'_description').hide();
return false;
}
function hide_error(input){
$('#'+input+'_tr').removeClass('tr_error');
$('#'+input+'_error').html('');
return true;
}
//show icon successful
function show_icon(input){
//$('#check_'+input).show();
//$('#check_'+input).fadeOut(2000);
return true;
}
function checkLen(str,min,max){
if((str.length > 0 && str.length < min) || str.length > max)
return false;
return true;
}
function trim(str){
return str.replace(/^\s+|\s+$/g, '');
}
function checkPassVietnam(str){
for(i=0;i<str.length;i++){
if(str.charCodeAt(i) < 32 || str.charCodeAt(i) > 126)
return false;
}
return true;
}
/* dungvv@vinagame.com.vn */
// check PP4-RM-Bussiness Rule Accountname
function checkInputChars(str) {
str = jQuery.trim(str);
var pattern = /^[a-z0-9](([a-z0-9])+|([a-z0-9][\_\.])*)[a-z0-9]$/;
if (str.match(pattern) != null) return true;
return false;
}
function isNumber(num) {
var pattern = /^\d+$/;
if (num.match(pattern) != null) return true;
else return false;
}
/*function showMsgError(arrMsg, msgId, msgText) {
for (i=0; i<arrMsg.length; i++) {
if (arrMsg[i] == msgId) {
$(msgId).text(msgText);
} else {
$(arrMsg[i]).text("");
}
}
}*/
/* end */
function checkVietNam(str){
for(i=0;i<str.length;i++){
if(str.charCodeAt(i) < 32 || str.charCodeAt(i) > 126)
return false;
}
return true;
}
function check_date_cmnd(){
var dd = $("#d_cmnd").val();
var mm = $("#m_cmnd").val();
var yyyy = $("#y_cmnd").val();
/*if(mm == -1)
mm = 1;
if(yyyy == '')
yyyy = 1990;
if(dd == '')
dd = 1;*/
if(!checkDate(dd,mm,yyyy)){
//showError('#d_cmnd',Persional_Error[1]);
return false;
}
hideError('#d_cmnd');
return true;
}
/* End ngay cap**/
/**Check ngay cap ###################################################################################*/
function CheckEmail(mailName,mailDomain,minlenMailName,minlenMailDomain,minlen,maxlen)
{
var sMailName = mailName.toLowerCase();
var sMailDomain = mailDomain.toLowerCase();
if(!sMailName || !sMailDomain)
return false;
if(sMailName.length < minlenMailName || sMailName.charAt(0) == '_' || sMailName.charAt(sMailName.length-1) == '_' || sMailName.indexOf('._') != -1 || sMailName.indexOf('_.') != -1 || sMailName.indexOf('__') != -1 || sMailName.indexOf('-') != -1)
{
return false;
}
if(sMailDomain.length < minlenMailDomain || sMailDomain.charAt(0) == '-' || sMailDomain.charAt(sMailDomain.length-1) == '-' || sMailDomain.indexOf('.-') != -1 || sMailDomain.indexOf('-.') != -1 || sMailDomain.indexOf('--') != -1 || sMailDomain.indexOf('_') != -1)
{
return false;
}
//
var stringIn = sMailName+'@'+sMailDomain ;
//
if(stringIn.length < minlen || stringIn.length > maxlen)
{
return false;
}
//
if (stringIn.indexOf('..') != -1 || stringIn.indexOf('.@') != -1 || stringIn.indexOf('@.') != -1 || stringIn.indexOf(':') != -1 )
{
return false;
}
var re = /^([A-Za-z0-9\_\-]+\.)*[A-Za-z0-9\_\-]+@[A-Za-z0-9\_\-]+(\.[A-Za-z0-9\_\-]+)+$/;
if (stringIn.search(re) == -1)
{
return false;
}
return true;
}
function checkPersonalId(str){
if(str.length < 8 || str.length > 15) {
return false;
}
if(!checkCharacter(str)){
return false;
}
return true;
}
function checkStringIsNum(str){
for(i=0;i<str.length;i++){
if(!checkNum(str.charCodeAt(i)))
return false;
}
return true;
}
function checkNum(c){
if(c > 47 && c < 58)
return true;
return false;
}
function checkDate(dd,mm,yyyy){
var mydate=new Date();
var year=mydate.getFullYear();
var month=mydate.getMonth() + 1;
var daym=mydate.getDate();
//alert(dd+' --- '+ daym);
//alert(mm+' --- '+ month);
//alert(yyyy+' --- '+ year);
//Kiem tra thoi gian hien tai
if(!checkStringIsNum(dd) || !checkStringIsNum(mm) || !checkStringIsNum(yyyy))
return false;
if(dd < 1 || dd > 31 || yyyy < 1900)
return false;
if(yyyy > year)
return false;
if(yyyy == year){
if(mm > month)
return false;
if(mm == month)
if(dd > daym || dd == daym)
return false;
}
//Kiem tra hop le
if(!isNaN(yyyy)&&(yyyy!="")&&(yyyy<10000)){
if ((mm==4 || mm==6 || mm==9 || mm==11) && dd==31)
return false;
if (mm == 2) { // check for february 29th
var isleap = (yyyy % 4 == 0 && (yyyy % 100 != 0 || yyyy % 400 == 0));
if (dd>29 || (dd==29 && !isleap))
return false;
}
}
return true;
}
function show_cmnd(){
$('#span_cmnd').html('-');
$('#tr_cmnd').show();
$('#tr_noicap_cmnd').show();
$('#tr_d_cmnd').show();
}
function hide_cmnd(){
$('#span_cmnd').html('+');
$('#tr_cmnd').hide();
$('#tr_noicap_cmnd').hide();
$('#tr_d_cmnd').hide();
}
// show error
function showError(obj,mess){
setValue(obj);
$(errId).html(mess);
showErrorHTML();
return true;
}
//Hide Error
function hideError(obj){
setValue(obj);
$(rId).removeClass();
$(labelId).removeClass();
$(trNoteId).removeClass();
$(errId).hide();
}
function setValue(obj){
rId = "#"+$(obj).attr('id')+"_tr";
labelId = "#"+$(obj).attr('id')+"_label";
trNoteId = "#"+$(obj).attr('id')+"_tr_note";
noteId = "#"+$(obj).attr('id')+"_note";
errId = "#"+$(obj).attr('id')+"_err";
}
function showErrorHTML(){
$(noteId).hide();
$(errId).show();
//$(trNoteId).removeClass("td_note");
$(trNoteId).addClass("td_note");
$(rId).addClass("tr_error");
}
function checkValid(obj){
$(obj).show();
$(obj).fadeOut(2000);
return true;
}
function password_level(str){
if(str.length < 6)
return false;
var level = new Array(null,null,null,null);
for(i=0;i<str.length;i++){
// Ky tu thuong
if(checkCharLow(str.charCodeAt(i)))
level[0] = 1;
// Ky tu hoa
if(checkCharUp(str.charCodeAt(i)))
level[1] = 1;
// Ky tu so
if(checkNum(str.charCodeAt(i)))
level[2] = 1;
}
//co ky tu dat biet
if(!checkCharacter(str)){
level[3] = 1;
}
return level;
}
function checkCharLow(c){
if(c > 96 && c < 123)
return true;
return false;
}
function checkCharUp(c){
if(c > 64 && c < 91)
return true;
return false;
}
function checkNum(c){
if(c > 47 && c < 58)
return true;
return false;
}
function checkCharacter(str){
for(i=0;i<str.length;i++){
if((str.charCodeAt(i) < 48 && str.charCodeAt(i) != 46)|| str.charCodeAt(i) > 122)
return false;
if(str.charCodeAt(i) > 57 && str.charCodeAt(i) < 65)
return false;
if(str.charCodeAt(i) > 90 && str.charCodeAt(i) < 97 && str.charCodeAt(i) != 95)
return false;
}
return true;
}
function resetMeta(){
$('#meta1').removeClass('meta');
$('#meta2').removeClass('meta');
$('#meta3').removeClass('meta');
$('#meta4').removeClass('meta');
}
function refreshImage() {
var datetime = new Date();
document.getElementById("sVerifyImg").src = "/imagesec/index."+datetime.getTime()+".html";
}
function checkImageSecurity(obj,minlen,chkAll){
if(!checkTextLengthStatic(trim(obj.value),minlen,obj)){
return false;
}
if(!checkImageSecurityChars(obj.value,obj,chkAll)){
return false;
}
return true;
}
function checkImageSecurityChars(str,obj,chkAll)
{
if(chkAll)
var re = /^[a-zA-Z]*$/;
else
var re = /^[a-z]*$/;
str = trim(str);
var pos = str.search(re);
if(pos == -1) {
return false;
}
else{
return true;
}
}
function checkTextLengthStatic(str,minlen,obj)
{
if(str.length!=minlen)
{
return false;
}
return true;
}
var is_valid = 0;
var cur_verify = '';
function checkImage(){
if(!$('#sVerifyCode').val())
return false;
if($('#sVerifyCode').val().length < 6){
chkVerifyCodeErr = 1;
showError('#sVerifyCode',Verify_Error[1])
return false;
}
if($('#sVerifyCode').val().length > 6)
return false;
is_valid = 1;
chkVerifyCodeErr = 0;
hideError('#sVerifyCode');
chkVerify = 1;
$('#sVerifyCode_tr_note').removeClass('td_note');
$('#sVerifyCode_note').hide();
checkValid("#sVerifyCode_icon");
return true;
//$('#sVerifyCode_wait').show();
var url = '/checkimage/index.html';
$.post(url, {sVerifyCode:$('#sVerifyCode').val()},
function(data){
$('#sVerifyCode_wait').hide();
if(data){
is_valid = 1;
chkVerifyCodeErr = 0;
hideError('#sVerifyCode');
chkVerify = 1;
$('#sVerifyCode_tr_note').removeClass('td_note');
$('#sVerifyCode_note').hide();
checkValid("#sVerifyCode_icon");
return true;
}else{
cur_verify = $('#sVerifyCode').val();
chkVerifyCodeErr = 1;
showError('#sVerifyCode',Verify_Error[0]);
return false;
}
}
);
}
$("#sVerifyCode").focus( function() {
if(this.value == ''){
hideError("#sVerifyCode")
}else{
}
} );
$("#sVerifyCode").keyup( function() {
if(this.value.length == 6){
checkImage();
}
} ); | JavaScript |
var JsLangZD = {
notic_title: "Thông báo",
alert_min_20_char: "Vui lòng điền ít nhất 20 ký tự",
alert_recharge_zing_xu: "Bạn đang nạp tiền vào tài khoản Zing Deal. Bạn có chắc chắn không?",
alert_choose_quantity: "Vui lòng chọn số lượng deal",
zing_id_not_allow: "Tài khoản không hợp lệ",
zing_id_exit: "Tài khoản đã tồn tại",
zing_id_ok: "Tài khoản hợp lệ",
share_width_friend: "Chia sẻ với bạn bè",
zmapp_share_default: "Mua hàng tiết kiệm với Zing Deal"
};
| JavaScript |
var Answer_confirm_error = "Xác nhận trả lời phải giống trả lời.";
function show_hide_password(){
var sAnswer_old = $('#sAnswer').val();
var flag = $('#sAnswer_confirm_tr').css("display");
var sAnswer_text = '<INPUT class="txt_260" id="sAnswer" onFocus="onFocus(this)" maxLength="100" name="sAnswer" type="text" tabindex="0" onblur="onBlurAnserRegister();" value="'+sAnswer_old+'" onChange="onChangeAnser1();">';
var sAnswer_pass = '<INPUT class="txt_260" id="sAnswer" onFocus="onFocus(this)" maxLength="100" name="sAnswer" type="password" tabindex="0" onblur="onBlurAnserRegister();">';
if(flag == 'none'){
$('#sAnswer_confirm_tr').show();
$("#sAnswer_update").html(sAnswer_pass);
$("#sAnswer").focus();
$('#answer_opt').html('Hiện chữ');
}else{
$('#sAnswer_confirm_tr').hide();
$("#sAnswer_update").html(sAnswer_text);
$("#sAnswer").focus();
$('#answer_opt').html('Ẩn chữ');
}
$('#sAnswer_confirm').val('');
hideError("#sAnswer_confirm");
$("#sAnswer").focus();
}
function onChangeAnser1(){
$("#sAnswer_confirm").val('');
hideError("#sAnswer_confirm");
}
function onBlurAnserRegister(){
hideError("#sAnswer");
var sAnswer = $('#sAnswer').val();
if(sAnswer != ''){
checkValid("#sAnswer_icon");
}else{
$("#sAnswer_confirm").val('');
hideError("#sAnswer_confirm");
}
$("#sAnswer_note").hide();
}
function onKeyUpConfirmAnswer(obj){
var sAnswer = $('#sAnswer').val();
var sAnswer_confirm = obj.value;
var flag = false;
if(sAnswer_confirm.length < sAnswer.length || sAnswer == ''){
//hideError("#sAnswer_confirm");
return false;
}
if(sAnswer_confirm.length == sAnswer.length){
if(sAnswer == obj.value){
checkValid("#sAnswer_confirm_icon");
flag = true;
}
}
if(flag){
hideError("#sAnswer_confirm");
}else{
$("#sAnswer_confirm_icon").hide();
showError('#sAnswer_confirm',Answer_confirm_error);
}
return true;
}
function onBlurConfirmAnswer(obj){
var sAnswer = $('#sAnswer').val();
var sAnswer_confirm = obj.value;
if(sAnswer == ''){
$('#sAnswer_confirm').val('');
hideError("#sAnswer_confirm");
}
if(sAnswer == '' && sAnswer_confirm == ''){
hideError("#sAnswer_confirm");
return false;
}
if(sAnswer != '' && sAnswer_confirm == ''){
showError('#sAnswer_confirm',Require_Error);
return false;
}
if(sAnswer == obj.value){
hideError("#sAnswer_confirm");
}else{
showError('#sAnswer_confirm',Answer_confirm_error);
}
return true;
}
function checkSubmitConfirmAnswer(){
hideNote('sAnswer');
var flag = $('#sAnswer_confirm_tr').css("display");
var sAnswer = $('#sAnswer').val();
var sAnswer_confirm = $('#sAnswer_confirm').val();
if(flag != 'none'){
if(sAnswer != ''){
if(sAnswer_confirm == ''){
showError('#sAnswer_confirm',Require_Error);
return false;
}
if(sAnswer_confirm != sAnswer){
showError('#sAnswer_confirm',Answer_confirm_error);
return false;
}
}
}
return true;
}
// dung cho cac form change Q&A, Update Account
function show_hide_password1(){
var sAnswer_old = $('#answer').val();
var flag = $('#answer_confirm_tr').css("display");
var answer_text = '<INPUT class="txt_260" id="answer" maxLength="100" name="answer" type="text" tabindex="1" onFocus="onfocusAnswer()" onblur="onBlurAnser();"value="'+sAnswer_old+'" onChange="onChangeAnser();" >';
var answer_pass = '<INPUT class="txt_260" id="answer" maxLength="100" name="answer" type="password" tabindex="1" onFocus="onfocusAnswer()" onblur="onBlurAnser();">';
if(flag == 'none'){
$('#answer_confirm_tr').show();
$("#answer_update").html(answer_pass);
$("#answer").focus();
$('#answer_opt').html('Hiện chữ');
}else{
$('#answer_confirm_tr').hide();
$("#answer_update").html(answer_text);
$("#answer").focus();
$('#answer_opt').html('Ẩn chữ');
}
$('#answer_confirm').val('');
hideError("#answer_confirm");
$("#answer").focus();
}
function onfocusAnswer(){
var answer = $('#answer').val();
if(answer == ''){
hideError("#answer");
$("#answer_tr_note").addClass("td_note");
$("#answer_note").show();
$('#answer_confirm').val('');
hideError("#answer_confirm");
}else{
onBlurAnser();
}
}
function onBlurAnser(){
hideError("#answer");
var answer = $('#answer').val();
if(answer != ''){
checkValid("#answer_icon");
}else{
hideError("#answer_confirm");
}
$("#answer_note").hide();
}
function onKeyUpConfirmAnswer1(obj){
var answer = $('#answer').val();
var answer_confirm = obj.value;
var flag = false;
if(answer_confirm.length < answer.length || answer == ''){
//hideError("#answer_confirm");
return false;
}
if(answer_confirm.length == answer.length){
if(answer == obj.value){
checkValid("#answer_confirm_icon");
flag = true;
}
}
if(flag){
hideError("#answer_confirm");
}else{
$("#answer_confirm_icon").hide();
showError('#answer_confirm',Answer_confirm_error);
}
return true;
}
function onBlurConfirmAnswer1(obj){
var answer = $('#answer').val();
var answer_confirm = obj.value;
if(answer == '' && answer_confirm == ''){
hideError("#answer_confirm");
return false;
}
if(answer != '' && answer_confirm == ''){
showError('#answer_confirm',Require_Error);
return false;
}
if(answer == obj.value){
hideError("#answer_confirm");
}else{
showError('#answer_confirm',Answer_confirm_error);
}
return true;
}
function checkSubmitConfirmAnswer1(){
var flag = $('#answer_confirm_tr').css("display");
var answer = $('#answer').val();
var answer_confirm = $('#answer_confirm').val();
if(flag != 'none'){
if(answer_confirm == ''){
showError('#answer_confirm',Require_Error);
return false;
}
if(answer_confirm != answer){
showError('#answer_confirm',Answer_confirm_error);
return false;
}
}
return true;
}
// dung cho cac form change Forgot
function show_hide_password2(){
var sAnswer_old = $('#answer').val();
var answer_text = '<INPUT class="txt_260" id="answer" maxLength="100" name="answer" type="text" tabindex="1" onblur="onBlurAnser();" value="'+sAnswer_old+'" onChange="onChangeAnser();">';
var answer_pass = '<INPUT class="txt_260" id="answer" maxLength="100" name="answer" type="password" tabindex="1" onblur="onBlurAnser();">';
var flag = $('#answer_opt').html();
if(flag == 'Ẩn chữ'){
$("#answer_update").html(answer_pass);
$("#answer").focus();
$('#answer_opt').html('Hiện chữ');
}else{
$("#answer_update").html(answer_text);
$("#answer").focus();
$('#answer_opt').html('Ẩn chữ');
}
$("#answer").focus();
}
function onChangeAnser(){
$("#answer_confirm").val('');
hideError("#answer_confirm");
}
////////
$("#question").focus( function() {
var is_forgot = $('#forgotpass_qna').val();
if(is_forgot == 'forgotpass_qna'){
hideError("#question");
return false;
}
if(this.value == -1){
hideError("#question");
//$('#answer').val('');
//$('#answer_confirm').val('');
$("#question_tr_note").addClass("td_note");
$("#question_note").show();
hideError("#answer_confirm");
hideError("#answer");
//$("#answer").val('');
//$("#answer_confirm").val('');
hideError('#sAnswer');
hideError('#sAnswer_confirm');
}
} );
$("#question").change( function() {
$("#sAnswer").val('');
$("#sAnswer_confirm").val('');
hideError('#sAnswer');
hideError('#sAnswer_confirm');
$("#answer").val('');
$("#answer_confirm").val('');
hideError('#answer');
hideError('#answer_confirm');
} );
$("#question").blur( function(){
$('#question_note').hide();
$("#question_tr_note").removeClass("td_note");
if($("#question").val()!=-1) {
checkValid("#question_icon");
}
} ); | JavaScript |
(function($) {
$.fn.aToolTip = function(options) {
/**
setup default settings
*/
var defaults = {
// no need to change/override
closeTipBtn: 'aToolTipCloseBtn',
toolTipId: 'aToolTip',
// ok to override
fixed: false,
clickIt: false,
inSpeed: 100,
outSpeed: 100,
tipContent: '',
toolTipClass: 'defaultTheme',
xOffset: 5,
yOffset: 5,
onShow: null,
onHide: null
},
// This makes it so the users custom options overrides the default ones
settings = $.extend({}, defaults, options);
return this.each(function() {
var obj = $(this);
/**
Decide weather to use a title attr as the tooltip content
*/
if(obj.attr('title')){
// set the tooltip content/text to be the obj title attribute
var tipContent = obj.attr('title');
} else {
// if no title attribute set it to the tipContent option in settings
var tipContent = settings.tipContent;
}
/**
Build the markup for aToolTip
*/
var buildaToolTip = function(){
$('body').append("<div id='"+settings.toolTipId+"' class='"+settings.toolTipClass+"'><p class='aToolTipContent'>"+tipContent+"</p></div>");
if(tipContent && settings.clickIt){
$('#'+settings.toolTipId+' p.aToolTipContent')
.append("<a id='"+settings.closeTipBtn+"' href='#' alt='close'>close</a>");
}
},
/**
Position aToolTip
*/
positionaToolTip = function(){
$('#'+settings.toolTipId).css({
top: (obj.offset().top - $('#'+settings.toolTipId).outerHeight() - settings.yOffset) + 'px',
left: (obj.offset().left + obj.outerWidth() + settings.xOffset) + 'px'
})
.stop().fadeIn(settings.inSpeed, function(){
if ($.isFunction(settings.onShow)){
settings.onShow(obj);
}
});
},
/**
Remove aToolTip
*/
removeaToolTip = function(){
// Fade out
$('#'+settings.toolTipId).stop().fadeOut(settings.outSpeed, function(){
$(this).remove();
if($.isFunction(settings.onHide)){
settings.onHide(obj);
}
});
};
/**
Decide what kind of tooltips to display
*/
// Regular aToolTip
if(tipContent && !settings.clickIt){
// Activate on hover
obj.hover(function(){
// remove already existing tooltip
$('#'+settings.toolTipId).remove();
obj.attr({title: ''});
buildaToolTip();
positionaToolTip();
}, function(){
removeaToolTip();
});
}
// Click activated aToolTip
if(tipContent && settings.clickIt){
// Activate on click
obj.click(function(el){
// remove already existing tooltip
$('#'+settings.toolTipId).remove();
obj.attr({title: ''});
buildaToolTip();
positionaToolTip();
// Click to close tooltip
$('#'+settings.closeTipBtn).click(function(){
removeaToolTip();
return false;
});
return false;
});
}
// Follow mouse if enabled
if(!settings.fixed && !settings.clickIt){
obj.mousemove(function(el){
$('#'+settings.toolTipId).css({
top: (el.pageY - $('#'+settings.toolTipId).outerHeight() - settings.yOffset),
left: (el.pageX + settings.xOffset)
});
});
}
}); // END: return this
};
})(jQuery); | JavaScript |
function queryString(parameter) {
var loc = location.search.substring(1, location.search.length);
var param_value = false;
var params = loc.split("&");
for (i=0; i<params.length;i++) {
param_name = params[i].substring(0,params[i].indexOf('='));
if (param_name == parameter) {
param_value = params[i].substring(params[i].indexOf('=')+1)
}
}
if (param_value) {
return param_value;
}
else {
return false;
}
}
var pid = queryString('pid'); // thay thế bằng tên param của product ID nếu khác
var eventid = queryString('eventid'); // thay thế bằng tên param của event ID nếu khác
var bannerid = queryString('bannerid'); // thay thế bằng tên param của banner ID nếu khác
var notTrackId = new Array("typeRegTopbar","typeDownload","guideReg","textReg","guideDownload","textDownload","typeReg","typePlayNow","typePromotion01","typePromotion02");
var notTrackLink = new Array("http://pay.zing.vn","https://pay.zing.vn","https://hotro1.zing.vn","http://hotro1.zing.vn");
var link_flash ="";
var link = "";
//var urlChoingay ="http://idgunny.zing.vn";
if (pid != false) {
link_flash += 'pid='+pid;
if (eventid!=false) {
link_flash+='%26eventid='+eventid;
}
if (bannerid!=false) {
link_flash +='%26bannerid='+bannerid;
}
}
function trackLink() {
setTimeout(function(){
if (pid!=false && eventid !=false && bannerid!=false){
//urlChoingay="https://app.zing.vn/UserClick/MainSite.php?type=152&eventid="+eventid+"&pid="+pid+"&bannerid="+bannerid;
if(guideReg && guideReg!=""){
var urlGuideReg = "https://app.zing.vn/UserClick/MainSite.php?type="+guideReg +"&eventid="+eventid+"&pid="+pid+"&bannerid="+bannerid;
jQuery("#guideReg").attr("href", urlGuideReg);;
}
if(textReg && textReg!=""){
var urlTextReg = "https://app.zing.vn/UserClick/MainSite.php?type="+textReg +"&eventid="+eventid+"&pid="+pid+"&bannerid="+bannerid;
jQuery("#textReg").attr("href", urlTextReg);;
}
if(guideDownload && guideDownload!=""){
var urlGuideDownload = "https://app.zing.vn/UserClick/MainSite.php?type="+guideDownload +"&eventid="+eventid+"&pid="+pid+"&bannerid="+bannerid;
jQuery("#guideDownload").attr("href", urlGuideDownload);;
}
if(textDownload && textDownload!=""){
var urlTextDownload = "https://app.zing.vn/UserClick/MainSite.php?type="+textDownload +"&eventid="+eventid+"&pid="+pid+"&bannerid="+bannerid;
jQuery("#textDownload").attr("href", urlTextDownload);;
}
if(typeReg && typeReg!= "") {
var urlReg="https://app.zing.vn/UserClick/MainSite.php?type="+typeReg +"&eventid="+eventid+"&pid="+pid+"&bannerid="+bannerid;
jQuery("#typeReg").attr("href", urlReg);
}
if(typeDownload && typeDownload!= "") {
var urlDownload="https://app.zing.vn/UserClick/MainSite.php?type="+typeDownload +"&eventid="+eventid+"&pid="+pid+"&bannerid="+bannerid;
jQuery("#typeDownload").attr("href", urlDownload);
}
if(typePromotion01 && typePromotion01 !=""){
var urlPromotion01="https://app.zing.vn/UserClick/MainSite.php?type="+typePromotion01 +"&eventid="+eventid+"&pid="+pid+"&bannerid="+bannerid;
jQuery("#typePromotion01").attr("href", urlPromotion01);
}
if(typePromotion02 && typePromotion02!=""){
var urlPromotion02="https://app.zing.vn/UserClick/MainSite.php?type="+typePromotion02 +"&eventid="+eventid+"&pid="+pid+"&bannerid="+bannerid;
jQuery("#typePromotion02").attr("href", urlPromotion02);
}
if(typeRegTopbar && typeRegTopbar!=""){
var urlRegTopbar="https://app.zing.vn/UserClick/MainSite.php?type="+typeRegTopbar +"&eventid="+eventid+"&pid="+pid+"&bannerid="+bannerid;
jQuery("#typeRegTopbar").attr("href", urlRegTopbar);
}
if(typePlayNow && typePlayNow!=""){
try{
var urlPlayNow =/* urlChoingay + */"https://app.zing.vn/UserClick/MainSite.php?type=" + typePlayNow +"&eventid="+eventid+"&pid="+pid+"&bannerid="+bannerid;
jQuery("#typePlayNow").attr("href", urlPlayNow);
} catch(exp){};
}
link='pid='+ pid + '&eventid='+ eventid + '&bannerid=' + bannerid;
}
jQuery("a").not(".notTrack").each(function (index) { // use class "notTrack" for untracking a
if(jQuery.inArray(jQuery(this).attr("id"), notTrackId) == -1){
var lnk = jQuery(this);
var href = lnk.attr("href");
for (k in notTrackLink){
if(!isNaN(k)){
var pattstr = "^"+notTrackLink[k];
var pattLink = new RegExp(pattstr,"i");
if(pattLink.test(href)){
return true;
}
}
}
if (href && href.charAt(0)!= "#" && link != ''){
lnk.attr("href", href + (href.indexOf("?") != -1 ? '&' : '?') + link);
}
}
});
},10);
} | JavaScript |
/**
* File JS for Promotion
*
* @author hungtd <hungtd@vng.com.vn>
*/
// onload jQuery
jQuery(document).ready(function($) {
// promotion click
$('a.JsPromotionDeal').click(function(event) {
event.preventDefault();
if (isUserLogin()) {
showAlertPromotion1105();
} else {
showFormQuickLogin();
}
});
// process promotion
$('.JsSubmitPromotionUserInfo').click(function () {
if ($('#DealUserPromotionName').val() == '') {
AlertZingDeal('Vui lòng điền tên của bạn.');
return false;
} else if ($('#DealUserPromotionPassport').val() == '') {
AlertZingDeal('Vui lòng điền chứng minh nhân dân của bạn.');
return false;
} else if ($('#DealUserPromotionPhone').val() == '') {
AlertZingDeal('Vui lòng điền số điện thoại của bạn.');
return false;
} else if ($('#DealUserPromotionEmail').val() == '') {
AlertZingDeal('Vui lòng địa chỉ email của bạn.');
return false;
} else if ($('#DealUserPromotionAddress').val() == '') {
AlertZingDeal('Vui lòng địa chỉ nhà hiện tại của bạn.');
return false;
} else if ($('#UserBirthday').val() == '') {
AlertZingDeal('Vui lòng điền sinh nhật của bạn.');
return false;
} else {
var htmldialog = '<div class="frmNapThe"><div>Chúng tôi sẽ dùng thông tin này để xác nhận trao giải cho bạn nếu bạn trúng thưởng. Bạn không thể thay đổi các thông tin trên khi hoàn tất quá trình này. <br /> Bạn có chắc chắn thông tin trên là chính xác ?</div>';
htmldialog += '<div style="padding-top:10px;text-align:center;"><input type="button" style="float:none;margin:0;" value=" " class="BtnXacNhan" onclick="submitFormPopup(\'#DealUserPromotionPromotion1105Form\');" /></div></div>';
AlertZingDeal(htmldialog);
return false;
}
});
if ($('.JsAmazingCampaign').length > 0) getBlockPromotion1105();
});
/**
* get block promotion 2011-05
*/
function getBlockPromotion1105()
{
$('.JsAmazingCampaign').html('<div style="text-align:center;"><img src="'+__cfg('path_absolute')+'static/img/themed/wothemes/loading_16x11.gif" align="center" /></div>');
$('.JsAmazingCampaign').show();
var aurl=__cfg('path_relative')+'deal_user_promotions/promotion1105block/'+Math.random();
$.get(aurl, function(data) {
$('.JsAmazingCampaign').html(data);
});
}
/**
* show popup promotion 2011-05
*/
function showAlertPromotion1105()
{
var htmldialog = '<div class="frmNapThe"><div>Bạn đang tham gia chương trình mua số may mắn của Zing Deal. <br /><br />Nếu bạn có lượt số may mắn miễn phí, Zing Deal sẽ trừ lượt số miễn phí của bạn.<br /><br /> Nếu bạn không có lượt số miễn phí Zing Deal sẽ khấu trừ tài khỏan của bạn. <br /><br />Bạn có chắc sẽ tham gia không ?</div>';
htmldialog += '<div style="padding-top:10px;text-align:center;"><input type="button" style="float:none;margin:0;" value=" " class="BtnXacNhan" onclick="changeToPromotion1105();" /></div></div>';
AlertZingDeal(htmldialog);
}
/**
* change to promotion 2011-05
*/
function changeToPromotion1105()
{
maskBlackDiv('.tbox .PopupContentFrm', 0);
var aurl = __cfg('path_relative')+'deal_user_promotions/promotion1105';
location.replace(aurl);
} | JavaScript |
var img_url = document.getElementById('img_url').value;
document.write(unescape("%3Cscript src='"+img_url+"keyboard/addKeyboard.js' type='text/javascript'%3E%3C/script%3E"));
//////////// Update 27/10/
var html_img_refresh = 'Nếu không đọc được, hãy nhấn vào <img border="0" align="texttop" src="'+img_url+'/images/iconRe.jpg" /> để đổi mã khác.';
$("#sVerifyCode").focus( function() {
if(this.value != '') return;
$('#sVerifyCode_tr_note').removeClass('td_note');
$('#sVerifyCode_note').hide();
$('#sVerifyCode_note').html('');
} );
$("#sVerifyCode").blur( function() {
if(this.value == ''){
$('#sVerifyCode_tr_note').removeClass('td_note');
$('#sVerifyCode_note').hide();
}
} );
////// End
/*-----------------------------
I/ SetHomePage
1/Chèn thẻ span này vào trang để thực hiện lấy giá trị homepage hiện thời
<span id="zing_homepage" style="behavior: url(#default#homepage); display: none;"></span>
2/Gọi hàm setHomePage() kiểm tra nếu homepage là họ *.zing.vn thì thôi - chỉ chạy trên IE
3/Gọi hàm addFavorite() để thêm domain hiện tại vào Bookmarks
II/ Hiển thị các sản phẩm họ Zing
1/ zshowHeader(innerID) để hiển thị trên header liên kết tới các sản phẩm *.zing
2/ zshowFooter(innerID) để nhảy tới sản phẩm *.zing trong combobox
innerID là tab chứa nội dung sẽ được hiển thị
3/ zshowCopyright(innerID) hiển thị copyright Zing
4/ zshowProducts(innerID) hiển thị các sản phẩm của Zing
ZingPortal
-----------------------------*/
function getCookies(name){
var start = document.cookie.indexOf( name + "=" );
var len = start + name.length + 1;
if ( ( !start ) && ( name != document.cookie.substring( 0, name.length ) ) )
return null;
if ( start == -1 )
return null;
var end = document.cookie.indexOf( ";", len );
if ( end == -1 )
end = document.cookie.length;
return unescape( document.cookie.substring( len, end ) );
};
/*-----------------------------*/
var url = 'http://' + window.location.host + '/';
var ZingD = ['www','chat','forum','id','mail','me','movie','mp3','pay','photo','play','star','video'];
var ZingT = ['Trang chủ Zing','Chat','Forum','ID','Mail','Me','Movie','Mp3','Pay','Photo','Play','Star','Video'];
/*
var ZingD = ['www','chat','forum','mail','movie','mp3','news','photo','star','video','yobanbe'];
var ZingT = ['Trang chủ Zing','Chat','Forum','Mail','Movie','Mp3','News','Photo','Star','Video','Yobanbe'];
*/
var ZingCopyright = 'Copyright © 2011 Zing<br />Đơn vị chủ quản: VNG Corporation <br />Giấy phép ICP số: 41/GP-TTĐT.';
/*-----------------------------*/
function setHomePage(){
if(document.all){
var homepage = document.getElementById('zing_homepage');
if(!homepage)
return;
var ishp = false;
for(var i=0;i<ZingD.length;i++) /*Check homepage*/
{
if(homepage.isHomePage('http://' + ZingD[i] + '.zing.vn/'))
{
ishp = true;
break;
}
}
if(!ishp){
homepage.style.behavior='url(#default#homepage)';
homepage.setHomePage(url); /*Set homepage*/
}
}
else
alert('Chọn Tools > Option > Main > Use Current Page (Alt+C) để đặt trang chủ!');
};
function addFavorite(){
var title='ZingPortal';
for(var i=0;i<ZingD.length;i++) /*Check homepage*/
{
if(url.indexOf(ZingD[i])>-1)
{
title = ZingT[i];
break;
}
}
if(document.all)
window.external.AddFavorite(url,title);
else if (window.sidebar)
window.sidebar.addPanel(title, url, "")
};
/*-----------------------------*/
function zshowHeader(dID){
dID = document.getElementById(dID);
if(!dID)
return;
var str ='';
for(var i=0;i<ZingD.length;i++)
{
var zd = ZingD[i];
var zt = ZingT[i];
if(zd=='mail')
str += '<a href="http://'+zd+'.zing.vn/cgi-bin/login?V=1011" target="_blank"><span id="zmail2711">'+zt+'</span></a> | ';
else if(zd=='www')
str += '<a href="http://'+zd+'.zing.vn/zing/index.aspx" target="_blank">'+zt+'</a> | ';
else
str += '<a href="http://'+zd+'.zing.vn" target="_blank">'+zt+'</a> | ';
}
dID.innerHTML = str + '<a href="http://123mua.com.vn" target="_blank">123Mua</a> | <a href="http://diendan.zing.vn/vng/index.php" target="_blank">Diễn đàn Game</a>';
};
function cboZfChange(_th){
var i = _th.selectedIndex;
if(i==0)
return;
window.open(_th[i].value);
};
function zshowFooter(dID){
dID = document.getElementById(dID);
if(!dID)
return;
var str ='<select onchange="cboZfChange(this);"><option value="">Các dịch vụ khác</option>';
for(var i=0;i<ZingD.length;i++)
str += '<option value="http://' + ZingD[i] + '.zing.vn">' + ZingT[i] + '</option>';
dID.innerHTML = str + '<option value="http://123mua.com.vn">123Mua</option></select>';
};
function zshowCopyright(dID){
dID = document.getElementById(dID);
if(!dID)
return;
dID.innerHTML = ZingCopyright;
/*----------------
var skey = getCookies('skey');
if(skey==null || skey=='')
return;
/*----------------
notify_new_mail();
var script = document.createElement("script");
script.setAttribute("src","http://mail.zing.vn/cgi-bin/unreadnum?callback=notify_new_mail");
script.setAttribute("type","text/javascript");
document.getElementsByTagName('head')[0].appendChild(script);
----------------*/
};
function zshowProducts(dID){
dID = document.getElementById(dID);
var img = img_url+'images/logozing_footer.png';
if(!dID)
return;
var str = '<p>Một dịch vụ của <img src="'+img+'" align="absmiddle" alt="Zing" longdesc="http://www.zing.vn/zing/" width="52" height="28"></p>';
str += '<p><select onchange="cboZfChange(this);"><option value="">Các dịch vụ khác</option>';
for(var i=0;i<ZingD.length;i++)
str += '<option value="http://' + ZingD[i] + '.zing.vn">' + ZingT[i] + '</option>';
dID.innerHTML = str + '<option value="http://123mua.com.vn">123Mua</option><option value="http://diendan.zing.vn/vng/index.php">Diễn đàn Game</option></select></p>';
};
function notify_new_mail(obj,containerID){
var unread=1;
if(obj){
if(obj.unread>=0)
unread = obj.unread;
}
if(typeof(containerID)==undefined || containerID==null)
containerID = 'zmail2711';
document.getElementById(containerID).innerHTML = 'Mail <b style="text-decoration:blink;">('+unread+')</b>';
};
zshowHeader('zingprod');
zshowProducts('footer_product');
zshowCopyright('footer_copy_right');
document.write(unescape("%3Cscript src='"+img_url+"js/jquery.tooltip.js' type='text/javascript'%3E%3C/script%3E"));
$(function() {
$("#foottip a").tooltip({
bodyHandler: function() {
return $($(this).attr("href")).html();
},
showURL: false, positionLeft: true
});
});
document.write(unescape("%3Cscript src='https://ssl.google-analytics.com/ga.js' type='text/javascript'%3E%3C/script%3E"));
document.write(unescape("%3Cscript src='"+img_url+"js/trackerGA.js' type='text/javascript'%3E%3C/script%3E"));
/*
Last update : 17/03/2009 - 4h00
*/ | JavaScript |
//lay message khuyn mai show len
var timer = '';
function getContent(type){
openBoxFeedback('fb',360,550);
$.ajaxSetup({
timeout: 10000
});
var content_feedback = $('#content_feedback').val();
var captcha_feedback = $('#captcha_feedback').val();
var verify_feedback = $('#verify_feedback').val();
var email_fb = $('#email_fb').val();
var cate_fb = $('#cate_fb').val();
var datetime = new Date();
var url = "/general/qna.38.fb."+datetime.getTime()+".html";
$.post(url, {
'type': type,
'content': content_feedback,
'captcha': captcha_feedback,
'email_fb': email_fb,
'cate_fb': cate_fb,
'verify': verify_feedback
},
function(json){
if(json['flag'] == 1){
$('#feedback').html(json['content']);
if(json['succ'] == 1){
timer = setTimeout("closeFeedback()",5000);
}else{
clearTimeout(timer);
$('#cate_fb').focus();
}
return false;
}
},'json'
);
}
function openFeedback(){
getContent(0);
}
function closeFeedback(){
$('#TB_overlay').hide();
$('#feedback').html('');
}
function submitFeedback(){
var content = $('#content_feedback').val();
var email_fb = $('#email_fb').val();
if(trim_(email_fb) != ''){
var re = /^([A-Za-z0-9\_\-]+\.)*[A-Za-z0-9\_\-]+@[A-Za-z0-9\_\-]+(\.[A-Za-z0-9\_\-]+)+$/;
if (email_fb.search(re) == -1){
$('#fb_err').html('Email phản hồi không hợp lệ.');
return false;
}
}
if(trim_(content) == ''){
$('#fb_err').html('Mời bạn nhập ý kiến đóng góp của mình.');
$('#content_feedback').val('')
return false;
}
getContent(1);
}
function openBoxFeedback(opt,width,height){
if (screen) {
var leftPos = (screen.width / 2) - (width/2)
var topPos = (screen.height / 2) - (height/2)
}
if(opt=='fb'){
$('#p_feedback').css("left",leftPos);
$('#p_feedback').css("top",topPos);
}
if(opt=='succ'){
$('#box_succ_register').css("left",leftPos);
$('#box_succ_register').css("top",topPos);
$('#box_succ_register').show();
}
if(opt=='verify'){
$('#box_verify_info').css("left",leftPos);
$('#box_verify_info').css("top",topPos);
$('#box_verify_info').show();
}
$('#TB_overlay').show();
setOverlay();
}
function setOverlay(){
var screenW = 640, screenH = 480;
if (parseInt(navigator.appVersion)>3) {
screenW = screen.width;
screenH = screen.height;
}
if (/Firefox[\/\s](\d+\.\d+)/.test(navigator.userAgent) || /Chrome[\/\s](\d+\.\d+)/.test(navigator.userAgent)){
$('#TB_overlay').addClass('fullscreenFF');
}else{
$('#TB_overlay').css("width",screenW+'.px');
$('#TB_overlay').css("height",screenH+'.px');
}
}
$(document).ready(function () {
var product_id = $('#product_id').val();
var product_url = $('#product_url').val();
var product_name = $('#product_name').val();
var view_box = $('#view_box').val();
if(view_box == 2){
openBoxFeedback('verify',882,550);
return;
}
if(view_box == 1){
openBoxFeedback('succ',882,550);
if(product_id != 38){
$('#is_product').show();
var str = '<br/><a href="'+product_url+'" >Quay về trang '+product_name+'</a>';
$('#is_product').html(str);
}
}
});
function closeBoxSuccess(){
$('#TB_overlay').hide();
$('#box_succ_register').hide();
}
function update_account_info(){
var product_id = $('#product_id').val();
act_pushUpdateInfo_GA();
document.location='/updateaccount/index.'+product_id+'.html';
}
function trim_(text)
{
var len=text.length;
var i=0;
var j=len-1;
var s="";
while(text.charAt(i)==" ")
i++;
while(text.charAt(j)==" ")
j--;
if(i>j)
s="";
else
s=text.substring(i,j+1);
return s;
}
| JavaScript |
var list_input = Array('password','email_name','question','answer','password2','cmnd','noicap','d_cmnd','m_cmnd','y_cmnd','verify_image','hoten','dienthoai','diachi','sSex_m','sSex_f');
/**Check ngay cap ###################################################################################*/
var hoten_invalid = "Họ tên phải có ít nhất 1 ký tự chữ.";
function check_require_field(){
//////////////////////
/////////////////////////////
if(trim($('#diachi').val()) == ''){
flag = false;
showError('#diachi','Địa chỉ không hợp lệ.');
}
if(trim($('#dienthoai').val()) == ''){
flag = false;
showError('#dienthoai','Số điện thoại không hợp lệ.');
}
////////////////////////////////
/////////////////////////
var frm = document.frmRegister ;
var list_input_require = new Array('password','email_name','password2','personalid','regionissue','d_cmnd','m_cmnd','y_cmnd','sVerifyCode','hoten','dienthoai','diachi');
var flag = true;
for(var i=0;i<list_input_require.length;i++){
if($('#'+list_input_require[i]).val() == ''){
$('#tr_'+list_input_require[i]).addClass('tr_error');
showError('#'+list_input_require[i],Require_Error);
flag = false;
}
}
if($("#email_name").val() != '' ){
if($('#sp_sel_domain').css('display') != 'none'){
if($("#email_domain").val() == '' || $("#email_domain").val() == -1) {
showError('#email_name',Require_Error);
flag = false;
}
}
if($('#sp_txt_domain').css('display') != 'none'){
$('#email_domain').val(-1);
if($("#email_domain_txt").val() == '') {
showError('#email_name',Require_Error);
flag = false;
}
}
}
if($("#regionissue").val() == -1) {
showError('#regionissue',Region_Error[0]);
flag = false;
}
if(!$('#sSex_m').is(':checked') && !$('#sSex_f').is(':checked')){
showError('#sSex_m',Require_Error);
flag = false;
}else{
hideError("#sSex_m");
}
if($("#dName").val() == -1 && $("#mName").val() == -1 && $("#yName").val() == -1) {
showError('#dName',Require_Error);
flag = false;
}
var cmnd = frm.elements["d_cmnd"];
if(cmnd) {
var d_cmnd = trim($('#d_cmnd').val());
var m_cmnd = trim($('#m_cmnd').val());
var y_cmnd = trim($('#y_cmnd').val());
if(d_cmnd == -1 && m_cmnd == -1 && y_cmnd == -1){
showError('#d_cmnd',Require_Error);
show_cmnd();
flag = false;
} else{
if(!checkDate(d_cmnd,m_cmnd,y_cmnd)){
showError('#d_cmnd',Persional_Error[1]);
flag = false;
}else{
hideError('#d_cmnd');
}
}
}
/** Update 09/08 **/
var maritalstatus_1 = document.getElementById('maritalstatus_1').checked;
var maritalstatus_2 = document.getElementById('maritalstatus_2').checked;
/*********/
if(maritalstatus_1 == false && maritalstatus_2 == false){
showError('#maritalstatus_1',Require_Error);
flag = false;
}else{
hideError('#maritalstatus_1');
}
var job = $('#job').val();
if(job==-1){
showError('#job',Require_Error);
flag = false;
}else{
hideError('#job');
}
var add = $('#add').val();
if(add==-1){
showError('#add',Require_Error);
flag = false;
}else{
hideError('#add');
}
/***
update
**/
return flag;
}
/**** Update maritalstatus *****/
$("#job").blur( function() {
if(trim(this.value) != -1) checkValid("#job_icon");
} );
$("#add").blur( function() {
if(trim(this.value) != -1) checkValid("#add_icon");
} );
$("#maritalstatus_1").click( function() {
hideError("#maritalstatus_1");
} );
$("#maritalstatus_2").click( function() {
hideError("#maritalstatus_1");
} );
$("#job").click( function() {
hideError("#job");
} );
$("#add").click( function() {
hideError("#add");
} );
/**********/
function hide_description(curent_input){
for(var i=0;i<list_input.length;i++){
if(list_input[i] != curent_input){
$('#description_'+list_input[i]).hide();
}
}
$('#tr_'+curent_input).removeClass('tr_error');
$('#error_'+curent_input).html('');
$('#description_'+curent_input).show();
}
function on_submit(){
var flag = true;
var flag_anser = checkSubmitConfirmAnswer1();
if(!check_require_field() || flag_anser == false)
{
return false;
}
else
{
//alert(2);
var password = $('#password').val();
var email_name = $('#email_name').val();
var email_domain = $('#email_domain').val();
var question = $('#question').val();
var answer = $('#answer').val();
var password2 = $('#password2').val();
var cmnd = $('#cmnd').val();
var d_cmnd = $('#d_cmnd').val();
var m_cmnd = $('#m_cmnd').val();
var y_cmnd = $('#y_cmnd').val();
var verify_image = $('#sVerifyCode').val();
var frm = document.frmRegister ;
if(password != '') {
if(!checkVietNam($('#password').val())){
showError('#password',Password_Error[0]);
flag = false;
} else if(!checkLen($('#password').val(),4,32)) {
showError('#password',Password_Error[1]);
flag = false;
} else {
hideError('#password');
}
}
var email = frm.elements["email_name"];
if(email) {
if(email_name != '') {
if(!check_email_name('#email_name')) {
flag = false;
} else {
hideError('#email_name');
}
}
}
if(!checkQuestion()) flag = false;
var cmnd = frm.elements["d_cmnd"];
if(cmnd) {
if(d_cmnd == -1 && m_cmnd == -1 && y_cmnd == -1){
showError('#d_cmnd',Require_Error);
show_cmnd();
flag = false;
} else {
if(!checkDate(d_cmnd,m_cmnd,y_cmnd)){
showError('#d_cmnd',Persional_Error[1]);
show_cmnd();
flag = false;
}else{
hideError('#d_cmnd');
}
}
}
var verify_code = frm.elements["sVerifyCode"];
if(verify_code){
var sVerifyCode = $('#sVerifyCode').val();
if(sVerifyCode.length != 6){
showError("#sVerifyCode",Verify_Error[1]);
flag = false;
}
else if(!checkImageSecurity(verify_code,6,true)) {
showError("#sVerifyCode",Verify_Error[1]);
flag = false;
}
}
}
if(checkStringIsNum($('#hoten').val())){
showError("#hoten",hoten_invalid);
flag = false;
}
if(checkDisplayError()) return false;
act_UpdateProfiePayer_GA();
if(flag) {
return true;
}
return false;
}
function checkDisplayError(){
var c1 = check_('password_err');
var c2 = check_('hoten_err');
var c3 = check_('sSex_m_err');
var c4 = check_('dName_err');
var c5 = check_('diachi_err');
var c6 = check_('dienthoai_err');
var c7 = check_('personalid_err');
var c8 = check_('d_cmnd_err');
var c9 = check_('regionissue_err');
var c10 = check_('sEmailName_err');
var c11 = check_('question_err');
var c12 = check_('answer_err');
var c13 = check_('sVerifyCode_err');
if(c1 || c2 || c3 || c4 || c5 || c6 || c7 || c8 || c9 || c10 || c11 || c12 || c13){
return true;
}
return false;
}
function check_(id){
if($('#'+id).css('display')){
if($('#'+id).css('display') != 'none'){
return true;
}
}
return false;
}
////////////////
$("#hoten").focus( function() {
//Update check
if(check_show_keyboard()) return true;
//End
hide_description('hoten');
if(this.value == ''){
hideError('#hoten');
}else{
}
} );
$("#diachi").focus( function() {
//Update check
if(check_show_keyboard()) return true;
//End
hide_description('diachi');
if(this.value == ''){
hideError('#diachi');
}else{
}
} );
$("#dienthoai").focus( function() {
//Update check
if(check_show_keyboard()) return true;
//End
hide_description('dienthoai');
if(this.value == ''){
hideError('#dienthoai');
}else{
}
} );
$("#sSex_m").focus( function() {
//Update check
if(check_show_keyboard()) return true;
//End
hide_description('sSex_m');
hideError('#sSex_m');
} );
$("#sSex_f").focus( function() {
//Update check
if(check_show_keyboard()) return true;
//End
hide_description('sSex_m');
hideError('#sSex_m');
} );
/*Check password*/
var flag_error_password = 0;
$("#password").focus( function() {
//Update check
if(check_show_keyboard()) return true;
//End
hide_description('password');
if(this.value == ''){
hideError('#password');
}else{
}
} );
$("#password").blur( function(){
//Update check
if(check_show_keyboard()) return true;
//End
return check_password(this);
} );
$("#password").keyup( function() {
} );
function check_password(obj){
if(!checkVietNam(obj.value)){
return showError(obj,Password_Error[0]);
}
if(!checkLen(obj.value,4,32)) {
return showError(obj,Password_Error[1]);
}
if(obj.value) {
checkValid("#password_icon");
}
return hideError(obj);
}
/*Check password*/
$("#email_name").focus( function() {
hide_description('email_name');
if(this.value == ''){
hideError("#email_name");
$("#email_name_tr_note").addClass("td_note");
$("#email_name_note").show();
}else{
//$(des).hide();
}
} );
$("#email_name").blur( function() {
$('#email_name_note').hide();
$("#email_name_tr_note").removeClass("td_note");
if(!check_email_name(this))
return false;
hideError(this);
} );
function check_email_name(obj){
var mailName = $("#email_name").val();
if($('#sp_sel_domain').css('display') != 'none'){
var mailDomain = $('#email_domain').val();
}
if($('#sp_txt_domain').css('display') != 'none'){
var mailDomain = $("#email_domain_txt").val();
}
if(mailDomain == '' || mailDomain == -1){
return false;
}
if(mailDomain=='zing.vn' && mailName == $('#accLogin').val()) {
showError(obj,'Không được trùng tên đăng nhập.');
return false;
}
var fullName = mailName+'@'+mailDomain;
if(!CheckEmail(mailName,mailDomain,2,4,7,100)){
showError(obj,Email_Error[0]);
return false;
}
hideError(obj);
return true;
}
$("#email_domain").blur( function() {
$('#email_name_note').hide();
$("#email_name_tr_note").removeClass("td_note");
if(!check_email_name($("#email_name"))) {
return false;
}
else {
checkValid("#email_name_icon");
}
} );
$("#email_domain_txt").blur( function() {
$('#email_name_note').hide();
$("#email_name_tr_note").removeClass("td_note");
if(!check_email_name($("#email_name")))
return false;
else
checkValid("#email_name_icon");
} );
$("#answer").focus( function() {
hide_description('answer');
if(this.value == '')
hideError("#answer");
$("#answer_tr_note").addClass("td_note");
$("#answer_note").show();
} );
$("#answer").blur( function(){
$('#answer_note').hide();
$("#answer_tr_note").removeClass("td_note");
if($("#answer").val()) {
checkValid("#answer_icon");
}
} );
$("#password2").focus( function() {
hide_description('password2');
if(this.value == ''){
hideError("#password2");
$("#password2_tr_note").addClass("td_note");
$("#password2_note").show();
}else{
}
} );
$("#password2").blur( function(){
$('#password2_note').hide();
return check_password2(this);
} );
function check_password2(obj){
if(!checkVietNam(obj.value)){
return showError(obj,Password_Error[0]);
}
if(!checkLen(obj.value,6,32)) {
return showError(obj,Password_Error[2]);
}
if(obj.value) {
checkValid("#password2_icon");
}
return hideError(obj);
}
$("#password2").keyup( function() {
if(!checkVietNam(this.value)){
chkPassErr = 1;
resetMeta();
return showError(this,Password_Error[0]);
}else{
if($("#sPassWord1_note").css('display') == 'none'){
chkPassErr = 0;
hideError(this);
}
}
if(this.value.length < 6){
resetMeta();
return false;
}
var level = password_level(this.value);
if(level){
//level 1
if((level[0] && !level[1] && !level[2] && !level[3])
|| (!level[0] && level[1] && !level[2] && !level[3])
|| (!level[0] && !level[1] && level[2] && !level[3])
|| (!level[0] && !level[1] && !level[2] && level[3])){
$('#meta1').addClass("meta");
}
//level 2
if((level[0] && level[1] && !level[2] && !level[3])
|| (level[0] && !level[1] && level[2] && !level[3])
|| (level[0] && !level[1] && !level[2] && level[3])
|| (!level[0] && level[1] && level[2] && !level[3])
|| (!level[0] && level[1] && !level[2] && level[3])
|| (!level[0] && !level[1] && level[2] && level[3])){
$('#meta1').addClass("meta");
$('#meta2').addClass("meta");
}else{
$('#meta2').removeClass("meta");
}
//level 3
if((level[0] && level[1] && level[2] && !level[3])
|| (level[0] && level[1] && !level[2] && level[3])
|| (level[0] && !level[1] && level[2] && level[3])
|| (!level[0] && level[1] && level[2] && level[3])){
$('#meta1').addClass("meta");
$('#meta2').addClass("meta");
$('#meta3').addClass("meta");
}
else{
$('#meta3').removeClass("meta");
}
//level 4
if(level[0] && level[1] && level[2] && level[3]){
$('#meta1').addClass("meta");
$('#meta2').addClass("meta");
$('#meta3').addClass("meta");
$('#meta4').addClass("meta");
}else{
$('#meta4').removeClass("meta");
}
}
} );
$("#personalid").focus( function() {
if(this.value == '')
hideError("#personalid");
$("#personalid_tr_note").addClass("td_note");
$("#personalid_note").show();
} );
$("#personalid").blur( function() {
$('#personalid_note').hide();
if(!checkPersonalId(this.value) && this.value.length > 0){
return showError(this,Persional_Error[0]);
}
if(this.value) {
checkValid("#personalid_icon");
}
hideError("#personalid");
} );
$("#regionissue").focus( function() {
if(this.value == -1)
hideError("#regionissue");
//$("#regionissue_tr_note").addClass("td_note");
$("#regionissue_note").show();
} );
$("#regionissue").blur( function(){
$('#regionissue_note').hide();
//$("#regionissue_tr_note").removeClass("td_note");
if($("#regionissue").val()!=-1) {
checkValid("#regionissue_icon");
}
} );
$("#noicap").focus( function() {
var des = '#description_noicap';
if(this.value == ''){
hide_description('noicap');
}else{
$(des).hide();
}
} );
function check_verify_image(){
var verify_image = $("#sVerifyCode").val();
if(verify_image != ''){
if(verify_image.length != 6){
return showError('#sVerifyCode',Verify_Error[0]);
}else{
hideError('#sVerifyCode');
return true;
}
}
return true;
}
$("#email_domain").change(
function(){
chkDomainSel = 1;
if(this.value == -1){
chkDomain = 1;
$('#sp_sel_domain').hide();
$('#sp_txt_domain').show();
$('#email_domain_txt').focus();
}
}
);
//################################################# EMAIL
function domainBlur(obj){
var mailName = $("#sEmailName").val();
var mailDomain = obj.value;
var fullName = mailName+'@'+mailDomain;
if(fullName == curAcc){
chkEmailErr = 1;
return showError('#sEmailName',Email_Error[2]);
}
if(mailDomain == '' || mailDomain == -1){
chkEmailErr = 0;
hideError('#sEmailName');
return false;
}
if(!CheckEmail(mailName,mailDomain,2,4,7,100)){
chkEmailErr = 1;
return showError('#sEmailName',Email_Error[0]);
}else{
if(curEmailname == mailName && curDomain == mailDomain)
return false;
//checkEmailAjax();
return false;
}
}
/* #################################### xu ly date #############################*/
var Date_invalid = Persional_Error[1];
$("#y_cmnd").blur( function() {
return checkDateValid('yyyy','d_cmnd','m_cmnd','y_cmnd',Date_invalid,1);
} );
$("#d_cmnd").blur( function() {
return checkDateValid('dd','d_cmnd','m_cmnd','y_cmnd',Date_invalid,1);
} );
$("#m_cmnd").blur( function() {
return checkDateValid('mm','d_cmnd','m_cmnd','y_cmnd',Date_invalid,1);
} );
//////////////////////////////////////////////////////////////////////////
var Date_invalid_birthday = 'Ngày sinh không hợp lệ.';
$("#yName").blur( function() {
return checkDateValid('yyyy','dName','mName','yName',Date_invalid_birthday,0);
} );
$("#dName").blur( function() {
return checkDateValid('dd','dName','mName','yName',Date_invalid_birthday,0);
} );
$("#mName").blur( function() {
return checkDateValid('mm','dName','mName','yName',Date_invalid_birthday,0);
} );
function checkDateValid(opt,dd,mm,yy,mess,cmnd){
var flag = 0;
var dd = $("#"+dd).val();
var mm = $("#"+mm).val();
var yyyy = $("#"+yy).val();
if(dd == -1 && mm==-1 && yyyy == -1){
if(cmnd == 1)
hideError('#d_cmnd');
else
hideError('#dName');
}
//neu blur ddd
if(opt == 'dd'){
if(mm != -1 && yyyy != -1){
if(!checkDate(dd,mm,yyyy) ){
if(cmnd == 1)
return showError('#d_cmnd',mess);
return showError('#dName',mess);
}else{
flag = 1;
}
}
}
//neu blur mm
if(opt == 'mm'){
if(yyyy != -1){
if(!checkDate(dd,mm,yyyy) ){
if(cmnd == 1)
return showError('#d_cmnd',mess);
return showError('#dName',mess);
}else{
flag = 1;
}
}
}
//neu blur yyyy
if(opt == 'yyyy'){
if(dd != -1 || mm != -1){
if(!checkDate(dd,mm,yyyy) ){
if(cmnd == 1)
return showError('#d_cmnd',mess);
return showError('#dName',mess);
}else{
flag = 1;
}
}
}
if(flag == 1){
if(cmnd == 1){
hideError('#d_cmnd');
return checkValid("#d_cmnd_icon");
}
hideError('#dName');
return checkValid("#dName_icon");
}
}
function checkStringIsNum(str){
for(i=0;i<str.length;i++){
if(!checkNum(str.charCodeAt(i)))
return false;
}
return true;
}
///////////////////// General ////////////////////////
function checkDate(dd,mm,yyyy){
var mydate=new Date();
var year=mydate.getFullYear();
var month=mydate.getMonth() + 1;
var daym=mydate.getDate();
if(!checkStringIsNum(dd) || !checkStringIsNum(mm) || !checkStringIsNum(yyyy))
return false;
//Kiem tra thoi gian hien tai
if(dd < 1 || dd > 31 || yyyy < 1900)
return false;
if(yyyy > year)
return false;
if(yyyy == year){
if(mm > month)
return false;
if(mm == month)
if(dd > daym || dd == daym)
return false;
}
//Kiem tra hop le
if(!isNaN(yyyy)&&(yyyy!="")&&(yyyy<10000)){
if ((mm==4 || mm==6 || mm==9 || mm==11) && dd==31)
return false;
if (mm == 2) { // check for february 29th
var isleap = (yyyy % 4 == 0 && (yyyy % 100 != 0 || yyyy % 400 == 0));
if (dd>29 || (dd==29 && !isleap))
return false;
}
}
return true;
}
//#################
$("#hoten").focus( function() {
if(this.value == ''){
hideError("#hoten");
}
} );
$("#hoten").blur( function() {
if(this.value == ''){
hideError("#hoten");
return;
}
if(checkStringIsNum(this.value)){
return showError("#hoten",hoten_invalid);
}
$('#hoten_note').hide();
$("#hoten_tr_note").removeClass("td_note");
if(trim(this.value) == "") {
return showError("#hoten",Require_Error);
} else if (this.value){
checkValid("#hoten_icon");
}
hideError("#hoten");
} );
$("#diachi").blur( function() {
hideError("#diachi");
if(trim(this.value) == ''){
return;
}
checkValid("#diachi_icon");
} );
$("#dienthoai").blur( function() {
if (trim(this.value) != ''){
if(!checkVietNam_tel(this.value))
showError('#dienthoai','Số điện thoại không hợp lệ.');
else{
hideError('#dienthoai');
checkValid("#dienthoai_icon");
}
}
} );
function checkVietNam_tel(str){
for(i=0;i<str.length;i++){
if(str.charCodeAt(i) < 32 || str.charCodeAt(i) > 126)
return false;
}
return true;
}
function checkQuestion(){
var question = $('#question').val();
var answer = $('#answer').val();
if(question){
if(question != -1){
if(answer == ''){
showError('#answer','Câu trả lời không hợp lệ.');
return false;
}
}
}
return true;
}
$("#answer").blur( function() {
if(trim(this.value) != ''){
checkValid("#answer_icon");
}
} );
function checkNum(c){
if(c > 47 && c < 58)
return true;
return false;
}
function checkStringIsNum(str){
for(i=0;i<str.length;i++){
if(!checkNum(str.charCodeAt(i)))
return false;
}
return true;
} | JavaScript |
/**
* File JS for Promotion
*
* @author hungtd <hungtd@vng.com.vn>
*/
// onload jQuery
jQuery(document).ready(function($) {
// promotion click
$('a.JsPromotionDeal').click(function(event) {
event.preventDefault();
if (isUserLogin()) {
showAlertPromotion1105();
} else {
showFormQuickLogin();
}
});
// process promotion
$('.JsSubmitPromotionUserInfo').click(function () {
if ($('#DealUserPromotionName').val() == '') {
AlertZingDeal('Vui lòng điền tên của bạn.');
return false;
} else if ($('#DealUserPromotionPassport').val() == '') {
AlertZingDeal('Vui lòng điền chứng minh nhân dân của bạn.');
return false;
} else if ($('#DealUserPromotionPhone').val() == '') {
AlertZingDeal('Vui lòng điền số điện thoại của bạn.');
return false;
} else if ($('#DealUserPromotionEmail').val() == '') {
AlertZingDeal('Vui lòng địa chỉ email của bạn.');
return false;
} else if ($('#DealUserPromotionAddress').val() == '') {
AlertZingDeal('Vui lòng địa chỉ nhà hiện tại của bạn.');
return false;
} else if ($('#UserBirthday').val() == '') {
AlertZingDeal('Vui lòng điền sinh nhật của bạn.');
return false;
} else {
var htmldialog = '<div class="frmNapThe"><div>Chúng tôi sẽ dùng thông tin này để xác nhận trao giải cho bạn nếu bạn trúng thưởng. Bạn không thể thay đổi các thông tin trên khi hoàn tất quá trình này. <br /> Bạn có chắc chắn thông tin trên là chính xác ?</div>';
htmldialog += '<div style="padding-top:10px;text-align:center;"><input type="button" style="float:none;margin:0;" value=" " class="BtnXacNhan" onclick="submitFormPopup(\'#DealUserPromotionPromotion1105Form\');" /></div></div>';
AlertZingDeal(htmldialog);
return false;
}
});
if ($('.JsAmazingCampaign').length > 0) getBlockPromotion1105();
});
/**
* get block promotion 2011-05
*/
function getBlockPromotion1105()
{
$('.JsAmazingCampaign').html('<div style="text-align:center;"><img src="'+__cfg('path_absolute')+'static/img/themed/wothemes/loading_16x11.gif" align="center" /></div>');
$('.JsAmazingCampaign').show();
var aurl=__cfg('path_relative')+'deal_user_promotions/promotion1105block/'+Math.random();
$.get(aurl, function(data) {
$('.JsAmazingCampaign').html(data);
});
}
/**
* show popup promotion 2011-05
*/
function showAlertPromotion1105()
{
var htmldialog = '<div class="frmNapThe"><div>Bạn đang tham gia chương trình mua số may mắn của Zing Deal. <br /><br />Nếu bạn có lượt số may mắn miễn phí, Zing Deal sẽ trừ lượt số miễn phí của bạn.<br /><br /> Nếu bạn không có lượt số miễn phí Zing Deal sẽ khấu trừ tài khỏan của bạn. <br /><br />Bạn có chắc sẽ tham gia không ?</div>';
htmldialog += '<div style="padding-top:10px;text-align:center;"><input type="button" style="float:none;margin:0;" value=" " class="BtnXacNhan" onclick="changeToPromotion1105();" /></div></div>';
AlertZingDeal(htmldialog);
}
/**
* change to promotion 2011-05
*/
function changeToPromotion1105()
{
maskBlackDiv('.tbox .PopupContentFrm', 0);
var aurl = __cfg('path_relative')+'deal_user_promotions/promotion1105';
location.replace(aurl);
} | JavaScript |
var list_input = new Array('password','new_password','confirm_new_password','verify_image');
/* #################################### xu ly password #############################*/
var chkPassErr = 0;
var chkConfirmPassErr = 0;
$("#password").focus( function() {
//Update check
if(check_show_keyboard()) return true;
//End
if(this.value == ''){
hideError('#password');
}else{
}
} );
$("#password").blur( function(){
//Update check
if(check_show_keyboard()) return true;
//End
return check_password(this);
} );
function check_password(obj){
if(!checkVietNam(obj.value)){
return showError(obj,Password_Error[0]);
}
if(!checkLen(obj.value,4,32)) {
return showError(obj,Password_Error[1]);
}
if(obj.value) {
checkValid("#password_icon");
}
return hideError(obj);
}
$("#new_password").focus( function() {
//Update check
if(check_show_keyboard()) return true;
//End
if(this.value == ''){
hideError("#new_password");
$("#new_password_tr_note").addClass("td_note");
$('#new_password_note').html(PASWORD_DESCRIPTION);
$("#new_password_note").show();
}else{
}
} );
$("#new_password").blur( function(){
if(this.value == ''){
return;
}
//Update check
if(check_show_keyboard()) return true;
//End
$('#new_password_note').hide();
hideError("#new_password");
if(this.value.length > 6){
show_Meta(this.value);
}
check_new_password(this);
} );
$("#new_password").change( function(){
$("#confirm_new_password").val('');
} );
function check_new_password(obj){
if($('#new_password').val() == ''){
return true;
}
if(!checkVietNam($('#new_password').val())){
showError(obj,Password_Error[0]);
return false
}
if(!checkLen($('#new_password').val(),6,32)) {
showError(obj,PASSWORD_ERR_NEW_LEN);
return false;
}
//update new password
if(!STRONG_PASSWORD){
showError(obj,PASSWORD_ERR_NEW);
return false;
}
//end
if(obj.value) {
checkValid("#new_password_icon");
}
return true;
}
$("#new_password").keyup( function() {
//Update check
if(check_show_keyboard()) return true;
//End
if(!checkVietNam(this.value)){
chkPassErr = 1;
resetMeta();
return showError(this,Password_Error[0]);
}else{
if($("#sPassWord1_note").css('display') == 'none'){
chkPassErr = 0;
hideError(this);
}
}
if(this.value.length < 6){
resetMeta();
return false;
}
show_Meta(this.value);
} );
$("#confirm_new_password").focus( function() {
//Update check
if(check_show_keyboard()) return true;
//End
if(this.value == ''){
hideError("#confirm_new_password")
}else{
}
} );
$("#confirm_new_password").blur( function(){
//Update check
if(check_show_keyboard()) return true;
//End
if(this.value == ''){
hideError("#confirm_new_password")
}else{
return check_confirm_new_password(this);
}
} );
function check_confirm_new_password(obj){
if(!checkLen($("#new_password").val(),6,32)) {
return false;
}
if($("#new_password").val() != $("#confirm_new_password").val()){
return showError(obj,Password_Error[3]);
}
if(obj.value) {
checkValid("#confirm_new_password_icon");
}
return hideError(obj);
}
function check_require_field(){
var check_valid = 0;
var list_input_require = new Array('password','new_password','confirm_new_password','sVerifyCode');
for(var i=0;i<list_input_require.length;i++){
if($('#'+list_input_require[i]).val() == ''){
$('#'+list_input_require[i]+'_tr').addClass('tr_error');
showError('#'+list_input_require[i],Require_Error);
check_valid = 1;
}
}
if(!check_new_password("#new_password")) {
check_valid = 1;
}
if($("#new_password").val() != $("#confirm_new_password").val()){
showError('confirm_new_password',Password_Error[4]);
check_valid = 1;
}
var frm = document.frmChangepass ;
var verify_code = frm.elements["sVerifyCode"];
if(verify_code){
if($("#sVerifyCode").val().length<1){
showError("#sVerifyCode",Require_Error);
check_valid = 1;
} else if(!checkImageSecurity(verify_code,6,true)) {
showError("#sVerifyCode",Verify_Error[1]);
check_valid = 1;
}
}
if(check_valid)
return false;
else
return true;
}
function on_submit(){
if(!check_require_field() || $('#password_err').css('display') != 'none' || $('#new_password_err').css('display') != 'none' || $('#confirm_new_password_err').css('display') != 'none' ){
return false;
}
else{
var frm = document.frmChangepass ;
var verify_code = frm.elements["sVerifyCode"];
if(verify_code){
if($('#sVerifyCode_err').css('display') != 'none'){
return false;
}
}
return true;
}
} | JavaScript |
var JsLangZD = {
notic_title: "Thông báo",
alert_min_20_char: "Vui lòng điền ít nhất 20 ký tự",
alert_recharge_zing_xu: "Bạn đang nạp tiền vào tài khoản Zing Deal. Bạn có chắc chắn không?",
alert_choose_quantity: "Vui lòng chọn số lượng deal",
zing_id_not_allow: "Tài khoản không hợp lệ",
zing_id_exit: "Tài khoản đã tồn tại",
zing_id_ok: "Tài khoản hợp lệ",
share_width_friend: "Chia sẻ với bạn bè",
zmapp_share_default: "Mua hàng tiết kiệm với Zing Deal"
};
| JavaScript |
function queryString(parameter) {
var loc = location.search.substring(1, location.search.length);
var param_value = false;
var params = loc.split("&");
for (i=0; i<params.length;i++) {
param_name = params[i].substring(0,params[i].indexOf('='));
if (param_name == parameter) {
param_value = params[i].substring(params[i].indexOf('=')+1)
}
}
if (param_value) {
return param_value;
}
else {
return false;
}
}
var pid = queryString('pid'); // thay thế bằng tên param của product ID nếu khác
var eventid = queryString('eventid'); // thay thế bằng tên param của event ID nếu khác
var bannerid = queryString('bannerid'); // thay thế bằng tên param của banner ID nếu khác
var notTrackId = new Array("typeRegTopbar","typeDownload","guideReg","textReg","guideDownload","textDownload","typeReg","typePlayNow","typePromotion01","typePromotion02");
var notTrackLink = new Array("http://pay.zing.vn","https://pay.zing.vn","https://hotro1.zing.vn","http://hotro1.zing.vn");
var link_flash ="";
var link = "";
//var urlChoingay ="http://idgunny.zing.vn";
if (pid != false) {
link_flash += 'pid='+pid;
if (eventid!=false) {
link_flash+='%26eventid='+eventid;
}
if (bannerid!=false) {
link_flash +='%26bannerid='+bannerid;
}
}
function trackLink() {
setTimeout(function(){
if (pid!=false && eventid !=false && bannerid!=false){
//urlChoingay="https://app.zing.vn/UserClick/MainSite.php?type=152&eventid="+eventid+"&pid="+pid+"&bannerid="+bannerid;
if(guideReg && guideReg!=""){
var urlGuideReg = "https://app.zing.vn/UserClick/MainSite.php?type="+guideReg +"&eventid="+eventid+"&pid="+pid+"&bannerid="+bannerid;
jQuery("#guideReg").attr("href", urlGuideReg);;
}
if(textReg && textReg!=""){
var urlTextReg = "https://app.zing.vn/UserClick/MainSite.php?type="+textReg +"&eventid="+eventid+"&pid="+pid+"&bannerid="+bannerid;
jQuery("#textReg").attr("href", urlTextReg);;
}
if(guideDownload && guideDownload!=""){
var urlGuideDownload = "https://app.zing.vn/UserClick/MainSite.php?type="+guideDownload +"&eventid="+eventid+"&pid="+pid+"&bannerid="+bannerid;
jQuery("#guideDownload").attr("href", urlGuideDownload);;
}
if(textDownload && textDownload!=""){
var urlTextDownload = "https://app.zing.vn/UserClick/MainSite.php?type="+textDownload +"&eventid="+eventid+"&pid="+pid+"&bannerid="+bannerid;
jQuery("#textDownload").attr("href", urlTextDownload);;
}
if(typeReg && typeReg!= "") {
var urlReg="https://app.zing.vn/UserClick/MainSite.php?type="+typeReg +"&eventid="+eventid+"&pid="+pid+"&bannerid="+bannerid;
jQuery("#typeReg").attr("href", urlReg);
}
if(typeDownload && typeDownload!= "") {
var urlDownload="https://app.zing.vn/UserClick/MainSite.php?type="+typeDownload +"&eventid="+eventid+"&pid="+pid+"&bannerid="+bannerid;
jQuery("#typeDownload").attr("href", urlDownload);
}
if(typePromotion01 && typePromotion01 !=""){
var urlPromotion01="https://app.zing.vn/UserClick/MainSite.php?type="+typePromotion01 +"&eventid="+eventid+"&pid="+pid+"&bannerid="+bannerid;
jQuery("#typePromotion01").attr("href", urlPromotion01);
}
if(typePromotion02 && typePromotion02!=""){
var urlPromotion02="https://app.zing.vn/UserClick/MainSite.php?type="+typePromotion02 +"&eventid="+eventid+"&pid="+pid+"&bannerid="+bannerid;
jQuery("#typePromotion02").attr("href", urlPromotion02);
}
if(typeRegTopbar && typeRegTopbar!=""){
var urlRegTopbar="https://app.zing.vn/UserClick/MainSite.php?type="+typeRegTopbar +"&eventid="+eventid+"&pid="+pid+"&bannerid="+bannerid;
jQuery("#typeRegTopbar").attr("href", urlRegTopbar);
}
if(typePlayNow && typePlayNow!=""){
try{
var urlPlayNow =/* urlChoingay + */"https://app.zing.vn/UserClick/MainSite.php?type=" + typePlayNow +"&eventid="+eventid+"&pid="+pid+"&bannerid="+bannerid;
jQuery("#typePlayNow").attr("href", urlPlayNow);
} catch(exp){};
}
link='pid='+ pid + '&eventid='+ eventid + '&bannerid=' + bannerid;
}
jQuery("a").not(".notTrack").each(function (index) { // use class "notTrack" for untracking a
if(jQuery.inArray(jQuery(this).attr("id"), notTrackId) == -1){
var lnk = jQuery(this);
var href = lnk.attr("href");
for (k in notTrackLink){
if(!isNaN(k)){
var pattstr = "^"+notTrackLink[k];
var pattLink = new RegExp(pattstr,"i");
if(pattLink.test(href)){
return true;
}
}
}
if (href && href.charAt(0)!= "#" && link != ''){
lnk.attr("href", href + (href.indexOf("?") != -1 ? '&' : '?') + link);
}
}
});
},10);
} | JavaScript |
/**
* Jquery ready
* Cac function javascript tren Zing Deal
*
* @author hungtd <hungtd@vng.com.vn>
*/
/**
* Ham check email
*/
function validateEmail(id)
{
var emailPattern = /^([a-zA-Z0-9_.-])+@([a-zA-Z0-9_.-])+\.([a-zA-Z])+([a-zA-Z])+/;
return emailPattern.test(id);
}
/**
* Ham check dien thoai di dong
*/
function validatePhone(id)
{
var phonePattern = /^(\+([0-9])+\s)*(([0-9])+([-])*([0-9])+)+$/;
return phonePattern.test(id);
}
/**
* check validate password form register
*/
function validatePasswordRule(pwd1, pwd2)
{
var kiem_tra = 0;
var chu_thuong = 0;
var chu_hoa = 0;
var ky_tu = 0;
var chu_so = 0;
if(pwd1.val() != "" && pwd1.val() == pwd2.val()) {
if(pwd1.val().length < 8 || pwd1.val().length > 32) {
AlertZingDeal("Lỗi: Mật khẩu phải có độ dài từ 8 đến 32 ký tự (>=8 và <=32)!");
return -1;
}
// kiem tra pass co chu so hay khong
re = /[0-9]/;
if(!re.test(pwd1.val())) chu_so = 1;
else chu_so = 1;
// kiem tra pass co chu thuong hay khong
re = /[a-z]/;
if(!re.test(pwd1.val())) chu_thuong = 1;
else chu_thuong = 1;
// kiem tra pass co chu hoa hay khong
re = /[A-Z]/;
if(!re.test(pwd1.val())) chu_hoa = 1;
else chu_hoa = 1;
// kiem tra pass cho ky tu dac biet hay khong
re = /[\W_]/;
if(!re.test(pwd1.val())) ky_tu = 1;
else ky_tu = 1;
} else {
AlertZingDeal("Lỗi: Xác nhận mật khẩu không chính xác!");
return -1;
}
kiem_tra = parseInt(chu_so) + parseInt(chu_thuong) + parseInt(chu_hoa) + parseInt(ky_tu);
if (kiem_tra < 3) return 0;
return 1;
}
/**
* check internet banking
*/
function checkIB()
{
var amount_min = 50000;
var amount_max = 100000000;
var amount_devide = 10000; //var amount_devide = 10000;
$('#ZingTransactionAmount').val($('#ZingTransactionAmount').val().replace(/\$|\,/g,''));
if ($("input[name='banking_service']:checked").val() < 1 || parseInt($('#ZingTransactionAmount').val()) < amount_min || $('#ZingTransactionAmount').val() == '' || parseInt($('#ZingTransactionAmount').val()) > amount_max || parseInt($('#ZingTransactionAmount').val()) % amount_devide != 0 || isNaN(parseInt($('#ZingTransactionAmount').val()))) {
var note = $('#account-not-exit').val();
if (parseInt($('#ZingTransactionAmount').val()) < amount_min) {
note = $('#alert-choose-amount-min').val();
} else if ($('#ZingTransactionAmount').val() == '' || isNaN(parseInt($('#ZingTransactionAmount').val()))) {
note = $('#alert-choose-amount').val();
} else if (parseInt($('#ZingTransactionAmount').val()) % amount_devide != 0) {
note = $('#alert-choose-amount-add').val();
} else if (parseInt($('#ZingTransactionAmount').val()) > amount_max) {
note = $('#alert-choose-amount-max').val();
}
AlertZingDeal(note);
$('#ZingTransactionAmount').val(formatCurrency($('#ZingTransactionAmount').val()));
return false;
}
return true;
}
/**
* Ham lay cookie
*/
function getCookie(c_name) {
if (document.cookie.length > 0) {
c_start = document.cookie.indexOf(c_name + '=');
if (c_start !=- 1) {
c_start = c_start + c_name.length + 1;
c_end = document.cookie.indexOf(';', c_start);
if (c_end ==- 1) {
c_end = document.cookie.length;
}
return unescape(document.cookie.substring(c_start, c_end));
}
}
return '';
}
/**
* HUNGTD
* format currency
*/
function formatCurrency(num) {
num = num.toString().replace(/\$|\,/g,'');
if(isNaN(num))
num = "0";
sign = (num == (num = Math.abs(num)));
num = Math.floor(num*100+0.50000000001);
cents = num%100;
num = Math.floor(num/100).toString();
if(cents<10)
cents = "0" + cents;
for (var i = 0; i < Math.floor((num.length-(1+i))/3); i++)
num = num.substring(0,num.length-(4*i+3))+','+ num.substring(num.length-(4*i+3));
//return (((sign)?'':'-') + '' + num + '.' + cents);
return (((sign)?'':'-') + '' + num);
}
/**
* hungtd - create cookie
*/
function createCookie(name,value,days) {
if (days) {
var date = new Date();
date.setTime(date.getTime()+(days*24*60*60*1000));
var expires = "; expires="+date.toGMTString();
}
else var expires = "";
document.cookie = name+"="+value+expires+"; path=/";
}
/**
* hungtd - read cookie
*/
function readCookie(c_name)
{
var i,x,y,ARRcookies=document.cookie.split(";");
for (i=0;i<ARRcookies.length;i++) {
x=ARRcookies[i].substr(0,ARRcookies[i].indexOf("="));
y=ARRcookies[i].substr(ARRcookies[i].indexOf("=")+1);
x=x.replace(/^\s+|\s+$/g,"");
if (x==c_name) {
return unescape(y);
}
}
return false;
}
/**
* hungtd - Get bought on deal view
*/
function getCountBought(deal_id)
{
var aurl=__cfg('path_relative')+'deals/zd_count_bought/'+deal_id+'/cache:'+Math.floor(Math.random()*10000);
var result = $.ajax({
type: "GET",
url: aurl,
data: '',
async: false
}).responseText;
if (result != 'ERROR') {
$('.zingdeal-number-bought').html(result);
}
}
/**
* hungtd - Charge Card to Zing Deal Amount
*/
function ChargeCardToZingDeal(user, seri, code, captcha)
{
maskBlackDiv('.tbox .PopupContentFrm');
var aurl=__cfg('path_relative')+'zing_transactions/zd_charge_card';
var result = $.ajax({
type: "GET",
url: aurl,
data: 'user='+user+'&zdseri='+seri+'&zdcode='+code+'&zdcaptcha='+captcha+'&cache='+Math.floor(Math.random()*10000),
async: false
}).responseText;
if (result == 'SUCCESS')
window.location.href = window.location.href;
}
/**
* hungtd - get balance for zing
*/
function getBalanceZing()
{
var aurl=__cfg('path_relative')+'users/zd_get_balance_zing/'+'cache:'+Math.floor(Math.random()*10000);
$.get(aurl, function(data) {
$('.JsBalance').html(formatCurrency(data));
});
}
/**
*
* huydm - validate email
**/
function validateSubscriptions()
{
var email = $('#SubscriptionEmail').val();
var reg = /^([a-zA-Z0-9_.-])+@([a-zA-Z0-9_.-])+\.([a-zA-Z])+([a-zA-Z])+/;
if(reg.test(email)){
return true;
} else {
alert('Error Email');
return false;
}
}
/**
* add email daily in ajax
*/
function AddEmailDailyAjax()
{
var email = $('#SubscriptionEmail').val();
var city_id = 44;
var user_id = 0;
var aurl=__cfg('path_relative')+'subscriptions/addmail';
var reg = /^([a-zA-Z0-9_.-])+@([a-zA-Z0-9_.-])+\.([a-zA-Z])+([a-zA-Z])+/;
if(reg.test(email)){
$.post(aurl, {email: email, city_id: city_id, user_id: user_id},
function(data){
alert(data);
});
} else {
alert('Xin nhập vào 1 email hợp lệ');
return;
}
}
/**
* hungtd - Track Deal
*/
function trackDeal(deal_id)
{
var aurl=__cfg('path_relative')+'deals/track_deal/'+deal_id+'/cache:'+Math.floor(Math.random()*10000);
$.get(aurl, function(data) {
data = data+'';
});
}
/**
* hungtd - notic error phone number
*/
function errorPhoneNumber()
{
}
/**
* hungtd - Add facebook
*/
function getLikeBoxFacebook(facebook)
{
var data = '<div style="height: 10px;"></div><div class="deal zingdeal-faq no-deal"><div class="deal-bg round-15 clearfix">'+facebook+'</div></div>';
$('.side2').append(data);
}
/**
* hungtd - Add Zing Me
*/
function getLikeBoxZingMe()
{
//var zingme = '<iframe scrolling="auto" frameborder="0" style="border: medium none; width: 230px; height: 339px;" allowtransparency="true" src="http://connect.me.zing.vn/vip/connect?uid=24868452"></iframe>';
//var data = '<div style="height: 10px;"></div><div class="deal zingdeal-faq no-deal"><div class="deal-bg round-15 clearfix"><div class="header-deal-next"><div class="icon-zingdeal"></div><h2><span class="h2">Zing Me</span></h2></div>'+zingme+'</div></div>';
//$('.side2').append(data);
}
/**
* hungtd - like this deal on facebook
*/
function likeThisDealToFaceBook(url)
{
var uri = encodeURI(url);
//alert(uri);
var data = '<iframe src="http://www.facebook.com/plugins/like.php?href='+uri+'&layout=standard&show_faces=false&width=450&action=like&font=tahoma&colorscheme=light&height=35" scrolling="no" frameborder="0" style="border:none; overflow:hidden; width:450px; height:35px;" allowTransparency="true"></iframe>';
$('#zingdeal-like-this-deal').html(data);
}
/**
* hungtd - like this deal on facebook Mobile
*/
function likeThisDealToFaceBookMB(url)
{
var uri = encodeURI(url);
//alert(uri);
var data = '<iframe src="http://www.facebook.com/plugins/like.php?href='+uri+'&layout=box_count&show_faces=true&width=100&action=like&font=arial&colorscheme=light&height=65" scrolling="no" frameborder="0" style="border:none; overflow:hidden; width:100px; height:65px;" allowTransparency="true"></iframe>';
$('#zingdeal-like-this-deal').html(data);
}
/**
* insert emoticon to discussion
*/
function insertEmoticon(a)
{
var r = $('#TopicDiscussionComment').val();
$('#TopicDiscussionComment').val(''+r+' '+a);
}
/* JS for order reservation*/
function showOrderResConfirm()
{
var value = jQuery('#DealBuyForm input:radio:checked').val();
if(value == 5){
$('#zingdeal-popup-order-reservation').show('slow');
return;
}
}
/**
* Danh sach user dat hang de thanh toan sau
*/
function list_order(){
var city = $('#OrderReservationCity').val();
var url = __cfg('path_absolute') + city + "/deal_user_tmps/list_order_reservation_ajax";
$.ajax({
url: url,
success: function (data){
$("#listOrderReservation").html(data);
}
}
);
}
/**
* COD confirm
*/
function CODConfirm()
{
var deal_id = $('#DealDealId').val();
var quantity = $('#DealQuantity').val();
$('.JsCODMethod').show();
$('.JsZingXuMethod').hide();
// load data frome ajax
var aurl=__cfg('path_relative')+'delivery_addresses/woadd/'+deal_id+'/quantity:'+quantity+'/cache:'+Math.floor(Math.random()*10000);
$.get(aurl, function(data) {
$('.JsCODMethod').html(data);
});
// end load data from ajax
}
// check and add COD Address
function checkCODAddress()
{
var i = 0;
i += ShowNoteForm('#DAName', 0);
i += ShowNoteForm('#DACityId', 0);
i += ShowNoteForm('#DADistrictId', 0);
i += ShowNoteForm('#DAWard', 0);
i += ShowNoteForm('#DAHouseNumber', 0);
i += ShowNoteForm('#DAStreetAddress', 0);
i += ShowNoteForm('#DAPhone', 1);
if (i == 7) {
if (!validatePhone($('#DAPhone').val())) {
$('#DAPhone').parent().children('.Note2').show();
return 0;
} else {
$('#DAPhone').parent().children('.Note2').hide();
return 1;
}
} else return 0;
}
// show note error of input form
function ShowNoteForm(form_input, is_note2)
{
if ($(form_input).val() == '') {
$(form_input).parent().children('.Note').show();
if (is_note2 == 1) $(form_input).parent().children('.Note2').hide();
return 0;
} else {
$(form_input).parent().children('.Note').hide();
return 1;
}
}
/**
* Add dia chi giao hang cua user va check confirm code
*/
function AddDeliveryAddress()
{
var confirm_code = '';
// get value confirm code
if ($('#input_confirm_cod_code').val() != '') confirm_code = $('#input_confirm_cod_code').val();
if ($('#input_confirm_cod_code_email').val() != '') confirm_code = $('#input_confirm_cod_code_email').val();
// check empty code
if (confirm_code == '') return;
// check COD confirm code
$('#status-send-confirm-code').hide();
$('#status-send-confirm-code').html(" ");
var deal_id = $('#DealDealId').val();
// check confirm code
maskBlackWindow(0);
$('#loading-send-confirm-code').attr('src', __cfg('path_static')+'static/img/blue-theme/loading_16x11.gif');
var aurl_checkcode = __cfg('path_relative')+'deal_user_tmps/check_code_confirm_cod/'+deal_id+'/'+confirm_code+'/address_id:'+$('#DeliveryAddressAddressId').val()+'/cache:'+Math.floor(Math.random()*10000);
$.get(aurl_checkcode, function(data_checkcode) {
if (data_checkcode == '1') {
// add Delivery address
saveDeliveryAddress(1);
} else {
maskBlackWindow(1);
$('#loading-send-confirm-code').attr('src', __cfg('path_static')+'static/img/blue-theme/img-line.png');
$('#status-send-confirm-code').html(data_checkcode);
$('#status-send-confirm-code').show();
}
});
// add dia chi giao hang
}
/**
* Add dia chi giao hang khong can check confirm code
*/
function AddDeliveryAddressNotConfirm()
{
maskBlackWindow(0);
saveDeliveryAddress(1);
}
// save ajax delivery address
function saveDeliveryAddress(show)
{
var aurl=__cfg('path_relative')+'delivery_addresses/woadd/'+'cache:'+Math.floor(Math.random()*10000);
$.post(aurl, {name: $('#DAName').val(), house_number: $('#DAHouseNumber').val(), street_address: $('#DAStreetAddress').val(), ward: $('#DAWard').val(), district_id: $('#DADistrictId').val(), message: $('#DAMessage').val(), phone: $('#DAPhone').val(), deliveryday: $('#DADeliveryDate').val(), auto_receive: $('#CheckRecieverOnCompany:checked').val(), receive_from: $('#DADeliveryFrom').val(), receive_to: $('#DADeliveryTo').val()},
function(data)
{
if (show == 1) {
// submit form mua hang
if (data >= 1) {
$('#DealBuyForm').submit();
}
else {
maskBlackWindow(1);
}
}
}
);
}
/**
* Tao mask black tren obj
*/
function maskBlackDiv(div, omaks)
{
if (omaks == 1)
$(div).unmask();
else
$(div).mask('Vui lòng chờ ...');
}
/**
* Tao man hinh black tren zing deal
*/
function maskBlackWindow(omaks) {maskBlackDiv('body', omaks);}
/**
* Xu ly phan user chon ngan hang de nap tin vao Zing Deal
*/
function chooseBanking(id) {
$('#'+id).attr('checked', true);
$('.listbanks li').removeClass('Active');
$('.'+id).addClass('Active');
}
/**
* Phan thanh toan qua COD
* Chuc nang gui ma xac don hang
*/
function SendConfirmCodeCOD()
{
// layout default
$('#status-send-confirm-code-email').hide();
$('#status-send-confirm-code-email').html(" ");
$('#loading-send-confirm-code-email').attr('src', __cfg('path_static')+'static/img/blue-theme/loading_16x11.gif');
// get data
var deal_id = $('#DealDealId').val();
var captchacodejs = $('#DeliveryAddressCaptcha').val();
var email = $('#DeliveryAddressEmail').val();
// check email
if (email == '' || !validateEmail(email)) {
$('#status-send-confirm-code-email').html('Bạn chưa điền địa chỉ email hoặc địa chỉ email của bạn không đúng. Vui lòng điền chính xác địa chỉ email của bạn.');
$('#status-send-confirm-code-email').show();
$('#loading-send-confirm-code-email').attr('src', __cfg('path_static')+'static/img/blue-theme/img-line.png');
} else {
var aurl=__cfg('path_relative')+'deal_user_tmps/confirmcod/'+deal_id+'/captchacode:'+captchacodejs+'/email:'+email+'/cache:'+Math.floor(Math.random()*10000);
$.get(aurl, function(data) {
$('#status-send-confirm-code-email').html(data);
$('#status-send-confirm-code-email').show();
$('#loading-send-confirm-code-email').attr('src', __cfg('path_static')+'static/img/blue-theme/img-line.png');
});
}
}
/**
* User cancel don hang COD
*/
function getConfirmCancelDelivery(id, page)
{
$('.delivery_id').val(id);
$('.delivery_page').val(page);
var htmltext = '<div class="frmNapThe"><div style="padding-bottom: 15px; text-align: center;">'+$('.question').val()+'</div>';
htmltext += '<div style="text-align: center;"><input type="button" class="BtnXacNhan" style="float:none;margin:0;" onClick="CancelDelivery(\''+id+'\', \''+page+'\')" value=" " /></div></div>';
AlertZingDeal(htmltext);
}
/**
* User cancel don hang COD
*/
function CancelDelivery(id, page)
{
var aurl=__cfg('path_relative')+'deal_user_tmps/cancel_delivery/'+Math.floor(Math.random()*10000000000);
$.post(aurl, {delivery_id: id},
function(data){
var status = data.substr(0 ,1);
var message = data.substr(1, data.length);
AlertZingDeal(message);
if (status == 1) {
window.location.href = window.location.href;
// var aurl2=__cfg('path_relative')+'deal_user_tmps/deliveryindex/'+Math.floor(Math.random()*10000000000)+'/page:'+page;
// $.get(aurl2, function(data2) {
// $('.JsAjaxContent').html(data2);
// AlertHide();
// });
}
});
}
// alert cho input
function alertInput(obj)
{
AlertZingDeal($(obj).attr('alert'));
}
// refresh captcha
function reCaptcha()
{
var nbran = Math.floor(Math.random()*10000000000);
$('#sVerifyImg').attr('src', __cfg('path_relative')+'static/img/blue-theme/loading_16x11.gif');
var aurl=__cfg('path_relative')+'deal_images/zd_captcha_charge/'+nbran;
$('#sVerifyImg').attr('src', aurl);
}
// Zing Deal popup
function PopUpZD(url_html, url)
{
if (url == 1) {
TINY.box.show({url:url_html,width:514,topsplit:3,fixed:false,animate:false});
} else {
TINY.box.show({html:url_html,width:514,topsplit:3,fixed:false,animate:false});
}
}
// alert cua Zing Deal
function AlertZingDeal(msg, title)
{
if (!title) {title = JsLangZD.notic_title}
var html_note = '<div class="InnerContent"><h3 class="TitleMain">'+title+'</h3><div class="PopupContentFrm">'+msg+'</div></div>';
PopUpZD(html_note, 0);
}
// set top
function AlertZingDealTop(msg, title, top)
{
if (!title) {title = JsLangZD.notic_title}
var html_note = '<div class="InnerContent"><h3 class="TitleMain">'+title+'</h3><div class="PopupContentFrm">'+msg+'</div></div>';
TINY.box.show({html:html_note,width:514,top:top,fixed:false,animate:false});
}
// hide alert Zing Deal
function AlertHide() {TINY.box.hide();$('.message').hide();}
/**
* Chuyen chuoi ngay thang nam sang Object cua javascript
*/
function strToOjectDate(date_time)
{
var arr_datetime = new Array();
var arr_date = new Array();
var arr_time = new Array();
arr_datetime = date_time.split(' ');
arr_date = arr_datetime[0].split('-');
arr_time = arr_datetime[1].split(':');
var austDay = new Date();
austDay = new Date(arr_date[0], arr_date[1]-1, arr_date[2], arr_time[0], arr_time[1], arr_time[2]);
return austDay;
}
// show childrend discussion
function childrentDiscussion(id)
{
var aurl=__cfg('path_relative')+'topic_discussions/children_discussion/'+id+'/cache:'+Math.floor(Math.random()*10000);
$.get(aurl, function(data) {
if (data != 'ERROR') {
$('#childrent-dicussion-'+id).html(data);
$('#childrent-dicussion-'+id).show();
}
});
}
// add topic discussion
function SendTopicComment(parent_id)
{
// get data
var topic_id = $('#TopicId').val();
var message = $('#TopicComment'+parent_id).val();
// check message
if (message.toString().replace(/\$|\ /g,'').length < 20) {
AlertZingDeal(JsLangZD.alert_min_20_char);
return false;
}
// check login
if (isUserLogin() == false) {
showFormQuickLogin();
return false;
}
// get url
var aurl=__cfg('path_relative')+'topic_discussions/ajaxadd/'+'cache:'+Math.floor(Math.random()*10000);
$.post(aurl, {parent_id: parent_id, topic_id: topic_id, message: message},
function(data){
$('#TopicComment'+parent_id).val('');
AlertZingDeal(data);
});
}
// show div
function ShowHideDiv(div_1, div_2) {$(div_1).show();$(div_2).hide();}
// submit form
function submitFormPopup(varform) {maskBlackWindow(0);$(varform).submit();}
// show form login nhanh
function showFormQuickLogin()
{
aurl=__cfg('path_relative')+'users/ajaxlogin';
PopUpZD(aurl, 1);
}
// check login cookie SSO
function isUserLogin()
{
var uin = getCookie('uin');
var username = getCookie('ZDUSERNAME');
if (uin || username) return true;
return false;
}
// function check
function checkGiftForm()
{
var i = 0;
i += ShowNoteForm(getFormValue('Jsgift_from', 0, 1));
i += ShowNoteForm(getFormValue('Jsgift_to', 0, 1));
i += ShowNoteForm(getFormValue('Jsgift_mail', 0, 1), 1);
i += ShowNoteForm(getFormValue('Jsgift_phone', 0, 1), 1);
if (i == 4) {
// check email
if (!validateEmail(getFormValue('Jsgift_mail'))) {
$(getFormValue('Jsgift_mail', 0, 1)).parent().children('.Note2').show();
return 0;
} else {
$(getFormValue('Jsgift_mail', 0, 1)).parent().children('.Note2').hide();
}
// check phone
if (!validatePhone(getFormValue('Jsgift_phone'))) {
$(getFormValue('Jsgift_phone', 0, 1)).parent().children('.Note2').show();
return 0;
} else {
$(getFormValue('Jsgift_phone', 0, 1)).parent().children('.Note2').hide();
}
return 1;
} else return 0;
}
// function get value form input
function getFormValue(name, isSelect, isObj)
{
if (isObj == 1) {
if (isSelect == 1) {
return 'select[name='+name+']';
} else {
return 'input[name='+name+']';
}
} else {
if (isSelect == 1) {
return $('select[name='+name+']').val();
} else {
return $('input[name='+name+']').val();
}
}
}
// check account Zing Deal
function checkAccountZingDeal(inputUsername)
{
var user = inputUsername.val();
// check value
if (user == '' || user.length < 4) {
inputUsername.css({border:"1px solid #FF0000"});
return false;
}
// status border
inputUsername.css({border:"1px solid #CFCFBD"});
// check by ajax
var aurl=__cfg('path_relative')+'zing_transactions/zd_check_user/'+user+'/cache:'+Math.floor(Math.random()*10000);
$.get(aurl, function(data) {
if (data == 'ERROR') {
inputUsername.css({border:"1px solid #FF0000"});
inputUsername.siblings('.Note').show();
} else {
inputUsername.css({border:"1px solid #89B4D6"});
inputUsername.siblings('.Note').hide();
}
});
}
// check account in Zing ID
function checkAccountZingID(inputUsername)
{
var user = inputUsername.val();
// check value
if (user == '' || user.length < 4) {
inputUsername.css({border:"1px solid #FF0000"});
return false;
}
// status border
inputUsername.css({border:"1px solid #CFCFBD"});
// check by ajax
var aurl=__cfg('path_relative')+'users/zd_check_user/'+user+'/cache:'+Math.floor(Math.random()*10000);
$.get(aurl, function(data) {
if (data == 'SUCCESS') {
inputUsername.css({border:"1px solid #89B4D6"});
inputUsername.siblings('.Note').show();
inputUsername.siblings('.Note').css("color", "#608BC0");
inputUsername.siblings('.Note').html(JsLangZD.zing_id_ok);
} else {
inputUsername.siblings('.Note').show();
inputUsername.siblings('.Note').css("color", "#FF0000");
inputUsername.css({border:"1px solid #FF0000"});
if (data == 'ERRORZD')
inputUsername.siblings('.Note').html(JsLangZD.zing_id_not_allow);
else inputUsername.siblings('.Note').html(JsLangZD.zing_id_exit);
}
});
}
// get string from date
// str <=> 'd-m-Y'
function toTimestamp(strDate)
{
if (strDate == '') return '';
var strFormat = formatDateUSA(strDate, '/');
var datum = Date.parse(strFormat);
return datum/1000;
}
// change d-m-Y => Y-m-d
function formatDateUSA(str, c)
{
var arr = str.split('-');
return arr[2] + c + arr[1] + c + arr[0];
}
// chọn các sub deal khác
function chooseOtherChildrenDeal(deal_parent_id)
{
var is_gift = parseInt($('#DealIsGift').val());
var $div = $('.JsBuyDealShowChildrenDeal');
var width = $div.parent().width() - 1;
$div.width(width);
var aurl=__cfg('path_relative')+'ajaxpages/choose_childrendeal/'+deal_parent_id+'/'+is_gift+'/cache:'+Math.floor(Math.random()*10000);
$div.load(aurl);
$div.show();
}
/* Customize heigh of iframe ZingMe*/
function zmGH() {
_document = window.document;
var newHeight;
if (isNaN(newHeight)) {
var body = _document.body;
var docEl = _document.documentElement;
if (_document.compatMode === 'CSS1Compat' && docEl.scrollHeight)
newHeight = docEl.scrollHeight;
else {
var sh = docEl.scrollHeight;
var oh = docEl.offsetHeight;
if (docEl.clientHeight !== oh) {
sh = body.scrollHeight;
oh = body.offsetHeight;
}
newHeight = sh;
}
}
return newHeight;
}
function zmResize(appname, h) {
if (h == undefined || h == null) h = zmGH();
var nh = "<iframe border=\"0\" style=\"display:none;\" src=\"http://me.zing.vn/rs_proxy.html?id=1#iframe_dst=parent&domain=zing.vn&message=" + appname + "#" + h + "\"></iframe>";
document.write(nh);
}
function ResizeFrame()
{
try {
var h = $('#ZingDealApp').height();
var options;// = {host: "zmapp.deal.zing.vn"};
zmXCall.resizeParent({id:"zingdeal", height: h+10}, options);
} catch (ex) {}
}
/* End customize heigh of iframe ZingMe*/ | JavaScript |
/*
* Superfish v1.4.8 - jQuery menu widget
* Copyright (c) 2008 Joel Birch
*
* Dual licensed under the MIT and GPL licenses:
* http://www.opensource.org/licenses/mit-license.html
* http://www.gnu.org/licenses/gpl.html
*
* CHANGELOG: http://users.tpg.com.au/j_birch/plugins/superfish/changelog.txt
*/
;(function($){
$.fn.superfish = function(op){
var sf = $.fn.superfish,
c = sf.c,
$arrow = $(['<span class="',c.arrowClass,'"> »</span>'].join('')),
over = function(){
var $$ = $(this), menu = getMenu($$);
clearTimeout(menu.sfTimer);
$$.showSuperfishUl().siblings().hideSuperfishUl();
},
out = function(){
var $$ = $(this), menu = getMenu($$), o = sf.op;
clearTimeout(menu.sfTimer);
menu.sfTimer=setTimeout(function(){
o.retainPath=($.inArray($$[0],o.$path)>-1);
$$.hideSuperfishUl();
if (o.$path.length && $$.parents(['li.',o.hoverClass].join('')).length<1){over.call(o.$path);}
},o.delay);
},
getMenu = function($menu){
var menu = $menu.parents(['ul.',c.menuClass,':first'].join(''))[0];
sf.op = sf.o[menu.serial];
return menu;
},
addArrow = function($a){ $a.addClass(c.anchorClass).append($arrow.clone()); };
return this.each(function() {
var s = this.serial = sf.o.length;
var o = $.extend({},sf.defaults,op);
o.$path = $('li.'+o.pathClass,this).slice(0,o.pathLevels).each(function(){
$(this).addClass([o.hoverClass,c.bcClass].join(' '))
.filter('li:has(ul)').removeClass(o.pathClass);
});
sf.o[s] = sf.op = o;
$('li:has(ul)',this)[($.fn.hoverIntent && !o.disableHI) ? 'hoverIntent' : 'hover'](over,out).each(function() {
if (o.autoArrows) addArrow( $('>a:first-child',this) );
})
.not('.'+c.bcClass)
.hideSuperfishUl();
var $a = $('a',this);
$a.each(function(i){
var $li = $a.eq(i).parents('li');
$a.eq(i).focus(function(){over.call($li);}).blur(function(){out.call($li);});
});
o.onInit.call(this);
}).each(function() {
var menuClasses = [c.menuClass];
if (sf.op.dropShadows && !($.browser.msie && $.browser.version < 7)) menuClasses.push(c.shadowClass);
$(this).addClass(menuClasses.join(' '));
});
};
var sf = $.fn.superfish;
sf.o = [];
sf.op = {};
sf.IE7fix = function(){
var o = sf.op;
if ($.browser.msie && $.browser.version > 6 && o.dropShadows && o.animation.opacity!=undefined)
this.toggleClass(sf.c.shadowClass+'-off');
};
sf.c = {
bcClass : 'sf-breadcrumb',
menuClass : 'sf-js-enabled',
anchorClass : 'sf-with-ul',
arrowClass : 'ui-icon-carat-1-s ui-icon',
shadowClass : 'sf-shadow'
};
sf.defaults = {
hoverClass : 'sfHover',
pathClass : 'overideThisToUse',
pathLevels : 1,
delay : 200,
animation : {opacity:'show'},
speed : 'fast',
autoArrows : true,
dropShadows : true,
disableHI : false, // true disables hoverIntent detection
onInit : function(){}, // callback functions
onBeforeShow: function(){},
onShow : function(){},
onHide : function(){}
};
$.fn.extend({
hideSuperfishUl : function(){
var o = sf.op,
not = (o.retainPath===true) ? o.$path : '';
o.retainPath = false;
var $ul = $(['li.',o.hoverClass].join(''),this).add(this).not(not).removeClass(o.hoverClass)
.find('>ul').hide().css('visibility','hidden');
o.onHide.call($ul);
return this;
},
showSuperfishUl : function(){
var o = sf.op,
sh = sf.c.shadowClass+'-off',
$ul = this.addClass(o.hoverClass)
.find('>ul:hidden').css('visibility','visible');
sf.IE7fix.call($ul);
o.onBeforeShow.call($ul);
$ul.animate(o.animation,o.speed,function(){ sf.IE7fix.call($ul); o.onShow.call($ul); });
return this;
}
});
})(jQuery); | JavaScript |
/**
* Cookie plugin
*
* Copyright (c) 2006 Klaus Hartl (stilbuero.de)
* Dual licensed under the MIT and GPL licenses:
* http://www.opensource.org/licenses/mit-license.php
* http://www.gnu.org/licenses/gpl.html
*
*/
/**
* Create a cookie with the given name and value and other optional parameters.
*
* @example $.cookie('the_cookie', 'the_value');
* @desc Set the value of a cookie.
* @example $.cookie('the_cookie', 'the_value', { expires: 7, path: '/', domain: 'jquery.com', secure: true });
* @desc Create a cookie with all available options.
* @example $.cookie('the_cookie', 'the_value');
* @desc Create a session cookie.
* @example $.cookie('the_cookie', null);
* @desc Delete a cookie by passing null as value. Keep in mind that you have to use the same path and domain
* used when the cookie was set.
*
* @param String name The name of the cookie.
* @param String value The value of the cookie.
* @param Object options An object literal containing key/value pairs to provide optional cookie attributes.
* @option Number|Date expires Either an integer specifying the expiration date from now on in days or a Date object.
* If a negative value is specified (e.g. a date in the past), the cookie will be deleted.
* If set to null or omitted, the cookie will be a session cookie and will not be retained
* when the the browser exits.
* @option String path The value of the path atribute of the cookie (default: path of page that created the cookie).
* @option String domain The value of the domain attribute of the cookie (default: domain of page that created the cookie).
* @option Boolean secure If true, the secure attribute of the cookie will be set and the cookie transmission will
* require a secure protocol (like HTTPS).
* @type undefined
*
* @name $.cookie
* @cat Plugins/Cookie
* @author Klaus Hartl/klaus.hartl@stilbuero.de
*/
/**
* Get the value of a cookie with the given name.
*
* @example $.cookie('the_cookie');
* @desc Get the value of a cookie.
*
* @param String name The name of the cookie.
* @return The value of the cookie.
* @type String
*
* @name $.cookie
* @cat Plugins/Cookie
* @author Klaus Hartl/klaus.hartl@stilbuero.de
*/
jQuery.cookie = function(name, value, options) {
if (typeof value != 'undefined') { // name and value given, set cookie
options = options || {};
if (value === null) {
value = '';
options = $.extend({}, options); // clone object since it's unexpected behavior if the expired property were changed
options.expires = -1;
}
var expires = '';
if (options.expires && (typeof options.expires == 'number' || options.expires.toUTCString)) {
var date;
if (typeof options.expires == 'number') {
date = new Date();
date.setTime(date.getTime() + (options.expires * 24 * 60 * 60 * 1000));
} else {
date = options.expires;
}
expires = '; expires=' + date.toUTCString(); // use expires attribute, max-age is not supported by IE
}
// NOTE Needed to parenthesize options.path and options.domain
// in the following expressions, otherwise they evaluate to undefined
// in the packed version for some reason...
var path = options.path ? '; path=' + (options.path) : '';
var domain = options.domain ? '; domain=' + (options.domain) : '';
var secure = options.secure ? '; secure' : '';
document.cookie = [name, '=', encodeURIComponent(value), expires, path, domain, secure].join('');
} else { // only name given, get cookie
var cookieValue = null;
if (document.cookie && document.cookie != '') {
var cookies = document.cookie.split(';');
for (var i = 0; i < cookies.length; i++) {
var cookie = jQuery.trim(cookies[i]);
// Does this cookie string begin with the name we want?
if (cookie.substring(0, name.length + 1) == (name + '=')) {
cookieValue = decodeURIComponent(cookie.substring(name.length + 1));
break;
}
}
}
return cookieValue;
}
}; | JavaScript |
$(document).ready(function() {
// Navigation menu
$('ul#navigation').superfish({
delay: 1000,
animation: {
opacity:'show',
height:'show'
},
speed: 'fast',
autoArrows: true,
dropShadows: false
});
$('ul#navigation li').hover(function(){
$(this).addClass('sfHover2');
},
function(){
$(this).removeClass('sfHover2');
});
// Accordion
$("#accordion, #accordion2").accordion({
header: "h3"
});
// Tabs
$('#tabs, #tabs2, #tabs5').tabs();
// Dialog
$('#dialog').dialog({
autoOpen: false,
width: 600,
bgiframe: false,
modal: false,
buttons: {
"Ok": function() {
$(this).dialog("close");
},
"Cancel": function() {
$(this).dialog("close");
}
}
});
// Login Dialog Link
$('#login_dialog').click(function(){
$('#login').dialog('open');
return false;
});
// Login Dialog
$('#login').dialog({
autoOpen: false,
width: 300,
height: 210,
bgiframe: true,
modal: true
/*
buttons: {
"Login": function() {
$(this).dialog("close");
},
"Close": function() {
$(this).dialog("close");
}
}
*/
});
// Dialog Link
$('#dialog_link').click(function(){
$('#dialog').dialog('open');
return false;
});
// Dialog auto open
$('#welcome').dialog({
autoOpen: true,
width: 470,
height: 180,
bgiframe: true,
modal: true,
buttons: {
"View Admintasia V1.0": function() {
$(this).dialog("close");
}
}
});
// Dialog auto open
$('#welcome_login').dialog({
autoOpen: true,
width: 370,
height: 430,
bgiframe: true,
modal: true,
buttons: {
"Proceed to demo !": function() {
window.location = "index.php";
}
}
});
// Datepicker
$('#datepicker').datepicker({
inline: true
});
//Hover states on the static widgets
$('#dialog_link, ul#icons li').hover(
function() {
$(this).addClass('ui-state-hover');
},
function() {
$(this).removeClass('ui-state-hover');
}
);
//Sortable
$(".column").sortable({
connectWith: '.column'
});
//Sidebar only sortable boxes
$(".side-col").sortable({
axis: 'y',
connectWith: '.side-col'
});
$(".portlet").addClass("ui-widget ui-widget-content ui-helper-clearfix ui-corner-all")
.find(".portlet-header")
.addClass("ui-widget-header")
.prepend('<span class="ui-icon ui-icon-circle-arrow-s"></span>')
.end()
.find(".portlet-content");
$(".portlet-header .ui-icon").click(function() {
$(this).toggleClass("ui-icon-circle-arrow-n");
$(this).parents(".portlet:first").find(".portlet-content").slideToggle();
});
$(".column").disableSelection();
/* Table Sorter */
$("#sort-table")
.tablesorter({
widgets: ['zebra'],
headers: {
// assign the secound column (we start counting zero)
0: {
// disable it by setting the property sorter to false
sorter: false
},
// assign the third column (we start counting zero)
6: {
// disable it by setting the property sorter to false
sorter: false
}
}
})
.tablesorterPager({
container: $("#pager")
});
$(".header").append('<span class="ui-icon ui-icon-carat-2-n-s"></span>');
});
/* Tooltip */
$(function() {
$('.tooltip').tooltip({
track: true,
delay: 0,
showURL: false,
showBody: " - ",
fade: 250
});
});
/* Theme changer - set cookie */
$(function() {
$("link[title='style']").attr("href","css/styles/default/ui.css");
$('a.set_theme').click(function() {
var theme_name = $(this).attr("id");
$("link[title='style']").attr("href","css/styles/" + theme_name + "/ui.css");
$.cookie('theme', theme_name );
$('a.set_theme').css("fontWeight","normal");
$(this).css("fontWeight","bold");
});
var theme = $.cookie('theme');
if (theme == 'default') {
$("link[title='style']").attr("href","css/styles/default/ui.css");
};
if (theme == 'light_blue') {
$("link[title='style']").attr("href","css/styles/light_blue/ui.css");
};
/* Layout option - Change layout from fluid to fixed with set cookie */
$("#fluid_layout a").click (function(){
$("#fluid_layout").hide();
$("#fixed_layout").show();
$("#page-wrapper").removeClass('fixed');
$.cookie('layout', 'fluid' );
});
$("#fixed_layout a").click (function(){
$("#fixed_layout").hide();
$("#fluid_layout").show();
$("#page-wrapper").addClass('fixed');
$.cookie('layout', 'fixed' );
});
var layout = $.cookie('layout');
if (layout == 'fixed') {
$("#fixed_layout").hide();
$("#fluid_layout").show();
$("#page-wrapper").addClass('fixed');
};
if (layout == 'fluid') {
$("#fixed_layout").show();
$("#fluid_layout").hide();
$("#page-wrapper").addClass('fluid');
};
});
/* Check all table rows */
var checkflag = "false";
function check(field) {
if (checkflag == "false") {
for (i = 0; i < field.length; i++) {
field[i].checked = true;
}
checkflag = "true";
return "check_all";
}
else {
for (i = 0; i < field.length; i++) {
field[i].checked = false;
}
checkflag = "false";
return "check_none";
}
}
checked=false;
function checkedAll (frm1) {
var aa= document.getElementById('UserList');
if (checked == false)
{
checked = true;
}
else
{
checked = false;
}
for (var i =0; i < aa.elements.length; i++)
{
aa.elements[i].checked = checked;
}
}
| JavaScript |
(function($) {
$.extend({
tablesorterPager: new function() {
function updatePageDisplay(c) {
var s = $(c.cssPageDisplay,c.container).val((c.page+1) + c.seperator + c.totalPages);
}
function setPageSize(table,size) {
var c = table.config;
c.size = size;
c.totalPages = Math.ceil(c.totalRows / c.size);
c.pagerPositionSet = false;
moveToPage(table);
fixPosition(table);
}
function fixPosition(table) {
var c = table.config;
if(!c.pagerPositionSet && c.positionFixed) {
var c = table.config, o = $(table);
if(o.offset) {
c.container.css({
//top: o.offset().top + o.height() + 'px',
//position: 'absolute'
});
}
c.pagerPositionSet = true;
}
}
function moveToFirstPage(table) {
var c = table.config;
c.page = 0;
moveToPage(table);
}
function moveToLastPage(table) {
var c = table.config;
c.page = (c.totalPages-1);
moveToPage(table);
}
function moveToNextPage(table) {
var c = table.config;
c.page++;
if(c.page >= (c.totalPages-1)) {
c.page = (c.totalPages-1);
}
moveToPage(table);
}
function moveToPrevPage(table) {
var c = table.config;
c.page--;
if(c.page <= 0) {
c.page = 0;
}
moveToPage(table);
}
function moveToPage(table) {
var c = table.config;
if(c.page < 0 || c.page > (c.totalPages-1)) {
c.page = 0;
}
renderTable(table,c.rowsCopy);
}
function renderTable(table,rows) {
var c = table.config;
var l = rows.length;
var s = (c.page * c.size);
var e = (s + c.size);
if(e > rows.length ) {
e = rows.length;
}
var tableBody = $(table.tBodies[0]);
// clear the table body
$.tablesorter.clearTableBody(table);
for(var i = s; i < e; i++) {
//tableBody.append(rows[i]);
var o = rows[i];
var l = o.length;
for(var j=0; j < l; j++) {
tableBody[0].appendChild(o[j]);
}
}
fixPosition(table,tableBody);
$(table).trigger("applyWidgets");
if( c.page >= c.totalPages ) {
moveToLastPage(table);
}
updatePageDisplay(c);
}
this.appender = function(table,rows) {
var c = table.config;
c.rowsCopy = rows;
c.totalRows = rows.length;
c.totalPages = Math.ceil(c.totalRows / c.size);
renderTable(table,rows);
};
this.defaults = {
size: 10,
offset: 0,
page: 0,
totalRows: 0,
totalPages: 0,
container: null,
cssNext: '.next',
cssPrev: '.prev',
cssFirst: '.first',
cssLast: '.last',
cssPageDisplay: '.pagedisplay',
cssPageSize: '.pagesize',
seperator: "/",
positionFixed: true,
appender: this.appender
};
this.construct = function(settings) {
return this.each(function() {
config = $.extend(this.config, $.tablesorterPager.defaults, settings);
var table = this, pager = config.container;
$(this).trigger("appendCache");
config.size = parseInt($(".pagesize",pager).val());
$(config.cssFirst,pager).click(function() {
moveToFirstPage(table);
return false;
});
$(config.cssNext,pager).click(function() {
moveToNextPage(table);
return false;
});
$(config.cssPrev,pager).click(function() {
moveToPrevPage(table);
return false;
});
$(config.cssLast,pager).click(function() {
moveToLastPage(table);
return false;
});
$(config.cssPageSize,pager).change(function() {
setPageSize(table,parseInt($(this).val()));
return false;
});
});
};
}
});
// extend plugin scope
$.fn.extend({
tablesorterPager: $.tablesorterPager.construct
});
})(jQuery); | JavaScript |
/************************************************************************************************************
JS Calendar
Copyright (C) September 2006 DTHMLGoodies.com, Alf Magne Kalleland
This library is free software; you can redistribute it and/or
modify it under the terms of the GNU Lesser General Public
License as published by the Free Software Foundation; either
version 2.1 of the License, or (at your option) any later version.
This library 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
Lesser General Public License for more details.
You should have received a copy of the GNU Lesser General Public
License along with this library; if not, write to the Free Software
Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
Dhtmlgoodies.com., hereby disclaims all copyright interest in this script
written by Alf Magne Kalleland.
Alf Magne Kalleland, 2006
Owner of DHTMLgoodies.com
************************************************************************************************************/
/* Update log:
(C) www.dhtmlgoodies.com, September 2005
Version 1.2, November 8th - 2005 - Added <iframe> background in IE
Version 1.3, November 12th - 2005 - Fixed top bar position in Opera 7
Version 1.4, December 28th - 2005 - Support for Spanish and Portuguese
Version 1.5, January 18th - 2006 - Fixed problem with next-previous buttons after a month has been selected from dropdown
Version 1.6, February 22nd - 2006 - Added variable which holds the path to images.
Format todays date at the bottom by use of the todayStringFormat variable
Pick todays date by clicking on todays date at the bottom of the calendar
Version 2.0 May, 25th - 2006 - Added support for time(hour and minutes) and changing year and hour when holding mouse over + and - options. (i.e. instead of click)
Version 2.1 July, 2nd - 2006 - Added support for more date formats(example: d.m.yyyy, i.e. one letter day and month).
// Modifications by Gregg Buntin
Version 2.1.1 8/9/2007 gfb - Add switch to turn off Year Span Selection
This allows me to only have this year & next year in the drop down
Version 2.1.2 8/30/2007 gfb - Add switch to start week on Sunday
Add switch to turn off week number display
Fix bug when using on an HTTPS page
*/
var turnOffYearSpan = false; // true = Only show This Year and Next, false = show +/- 5 years
var weekStartsOnSunday = false; // true = Start the week on Sunday, false = start the week on Monday
var showWeekNumber = true; // true = show week number, false = do not show week number
var languageCode = 'en'; // Possible values: en,ge,no,nl,es,pt-br,fr
// en = english, ge = german, no = norwegian,nl = dutch, es = spanish, pt-br = portuguese, fr = french, da = danish, hu = hungarian(Use UTF-8 doctype for hungarian)
var calendar_display_time = true;
// Format of current day at the bottom of the calendar
// [todayString] = the value of todayString
// [dayString] = day of week (examle: mon, tue, wed...)
// [UCFdayString] = day of week (examle: Mon, Tue, Wed...) ( First letter in uppercase)
// [day] = Day of month, 1..31
// [monthString] = Name of current month
// [year] = Current year
var todayStringFormat = '[todayString] [UCFdayString]. [day]. [monthString] [year]';
var pathToImages = 'Admin/calendar/images/'; // Relative to your HTML file
var speedOfSelectBoxSliding = 200; // Milliseconds between changing year and hour when holding mouse over "-" and "+" - lower value = faster
var intervalSelectBox_minutes = 5; // Minute select box - interval between each option (5 = default)
var calendar_offsetTop = 0; // Offset - calendar placement - You probably have to modify this value if you're not using a strict doctype
var calendar_offsetLeft = 0; // Offset - calendar placement - You probably have to modify this value if you're not using a strict doctype
var calendarDiv = false;
var MSIE = false;
var Opera = false;
if(navigator.userAgent.indexOf('MSIE')>=0 && navigator.userAgent.indexOf('Opera')<0)MSIE=true;
if(navigator.userAgent.indexOf('Opera')>=0)Opera=true;
switch(languageCode){
case "en": /* English */
var monthArray = ['January','February','March','April','May','June','July','August','September','October','November','December'];
var monthArrayShort = ['Jan','Feb','Mar','Apr','May','Jun','Jul','Aug','Sep','Oct','Nov','Dec'];
var dayArray = ['Mon','Tue','Wed','Thu','Fri','Sat','Sun'];
var weekString = 'Week';
var todayString = '';
break;
case "ge": /* German */
var monthArray = ['Januar','Februar','M�rz','April','Mai','Juni','Juli','August','September','Oktober','November','Dezember'];
var monthArrayShort = ['Jan','Feb','Mar','Apr','Mai','Jun','Jul','Aug','Sep','Okt','Nov','Dez'];
var dayArray = ['Mon','Die','Mit','Don','Fre','Sam','Son'];
var weekString = 'Woche';
var todayString = 'Heute';
break;
case "no": /* Norwegian */
var monthArray = ['Januar','Februar','Mars','April','Mai','Juni','Juli','August','September','Oktober','November','Desember'];
var monthArrayShort = ['Jan','Feb','Mar','Apr','Mai','Jun','Jul','Aug','Sep','Okt','Nov','Des'];
var dayArray = ['Man','Tir','Ons','Tor','Fre','Lør','Søn'];
var weekString = 'Uke';
var todayString = 'Dagen i dag er';
break;
case "nl": /* Dutch */
var monthArray = ['Januari','Februari','Maart','April','Mei','Juni','Juli','Augustus','September','Oktober','November','December'];
var monthArrayShort = ['Jan','Feb','Mar','Apr','Mei','Jun','Jul','Aug','Sep','Okt','Nov','Dec'];
var dayArray = ['Ma','Di','Wo','Do','Vr','Za','Zo'];
var weekString = 'Week';
var todayString = 'Vandaag';
break;
case "es": /* Spanish */
var monthArray = ['Enero','Febrero','Marzo','April','Mayo','Junio','Julio','Agosto','Septiembre','Octubre','Noviembre','Diciembre'];
var monthArrayShort =['Ene','Feb','Mar','Abr','May','Jun','Jul','Ago','Sep','Oct','Nov','Dic'];
var dayArray = ['Lun','Mar','Mie','Jue','Vie','Sab','Dom'];
var weekString = 'Semana';
var todayString = 'Hoy es';
break;
case "pt-br": /* Brazilian portuguese (pt-br) */
var monthArray = ['Janeiro','Fevereiro','Março','Abril','Maio','Junho','Julho','Agosto','Setembro','Outubro','Novembro','Dezembro'];
var monthArrayShort = ['Jan','Fev','Mar','Abr','Mai','Jun','Jul','Ago','Set','Out','Nov','Dez'];
var dayArray = ['Seg','Ter','Qua','Qui','Sex','Sáb','Dom'];
var weekString = 'Sem.';
var todayString = 'Hoje é';
break;
case "fr": /* French */
var monthArray = ['Janvier','F�vrier','Mars','Avril','Mai','Juin','Juillet','Ao�t','Septembre','Octobre','Novembre','D�cembre'];
var monthArrayShort = ['Jan','Fev','Mar','Avr','Mai','Jun','Jul','Aou','Sep','Oct','Nov','Dec'];
var dayArray = ['Lun','Mar','Mer','Jeu','Ven','Sam','Dim'];
var weekString = 'Sem';
var todayString = "Aujourd'hui";
break;
case "da": /*Danish*/
var monthArray = ['januar','februar','marts','april','maj','juni','juli','august','september','oktober','november','december'];
var monthArrayShort = ['jan','feb','mar','apr','maj','jun','jul','aug','sep','okt','nov','dec'];
var dayArray = ['man','tirs','ons','tors','fre','lør','søn'];
var weekString = 'Uge';
var todayString = 'I dag er den';
break;
case "hu": /* Hungarian - Remember to use UTF-8 encoding, i.e. the <meta> tag */
var monthArray = ['Január','Február','Március','�?prilis','Május','Június','Július','Augusztus','Szeptember','Október','November','December'];
var monthArrayShort = ['Jan','Feb','Márc','�?pr','Máj','Jún','Júl','Aug','Szep','Okt','Nov','Dec'];
var dayArray = ['Hé','Ke','Sze','Cs','Pé','Szo','Vas'];
var weekString = 'Hét';
var todayString = 'Mai nap';
break;
case "it": /* Italian*/
var monthArray = ['Gennaio','Febbraio','Marzo','Aprile','Maggio','Giugno','Luglio','Agosto','Settembre','Ottobre','Novembre','Dicembre'];
var monthArrayShort = ['Gen','Feb','Mar','Apr','Mag','Giu','Lugl','Ago','Set','Ott','Nov','Dic'];
var dayArray = ['Lun',';Mar','Mer','Gio','Ven','Sab','Dom'];
var weekString = 'Settimana';
var todayString = 'Oggi è il';
break;
case "sv": /* Swedish */
var monthArray = ['Januari','Februari','Mars','April','Maj','Juni','Juli','Augusti','September','Oktober','November','December'];
var monthArrayShort = ['Jan','Feb','Mar','Apr','Maj','Jun','Jul','Aug','Sep','Okt','Nov','Dec'];
var dayArray = ['Mån','Tis','Ons','Tor','Fre','Lör','Sön'];
var weekString = 'Vecka';
var todayString = 'Idag är det den';
break;
case "cz": /* Czech */
var monthArray = ['leden','únor','březen','duben','květen','červen','červenec','srpen','září','říjen','listopad','prosinec'];
var monthArrayShort = ['led','ún','bř','dub','kvě','čer','čer-ec','srp','zář','říj','list','pros'];
var dayArray = ['Pon','Út','St','Čt','Pá','So','Ne'];
var weekString = 'týden';
var todayString = '';
break;
}
if (weekStartsOnSunday) {
var tempDayName = dayArray[6];
for(var theIx = 6; theIx > 0; theIx--) {
dayArray[theIx] = dayArray[theIx-1];
}
dayArray[0] = tempDayName;
}
var daysInMonthArray = [31,28,31,30,31,30,31,31,30,31,30,31];
var currentMonth;
var currentYear;
var currentHour;
var currentMinute;
var calendarContentDiv;
var returnDateTo;
var returnFormat;
var activeSelectBoxMonth;
var activeSelectBoxYear;
var activeSelectBoxHour;
var activeSelectBoxMinute;
var iframeObj = false;
//// fix for EI frame problem on time dropdowns 09/30/2006
var iframeObj2 =false;
function EIS_FIX_EI1(where2fixit)
{
if(!iframeObj2)return;
iframeObj2.style.display = 'block';
iframeObj2.style.height =document.getElementById(where2fixit).offsetHeight+1;
iframeObj2.style.width=document.getElementById(where2fixit).offsetWidth;
iframeObj2.style.left=getleftPos(document.getElementById(where2fixit))+1-calendar_offsetLeft;
iframeObj2.style.top=getTopPos(document.getElementById(where2fixit))-document.getElementById(where2fixit).offsetHeight-calendar_offsetTop;
}
function EIS_Hide_Frame()
{ if(iframeObj2)iframeObj2.style.display = 'none';}
//// fix for EI frame problem on time dropdowns 09/30/2006
var returnDateToYear;
var returnDateToMonth;
var returnDateToDay;
var returnDateToHour;
var returnDateToMinute;
var inputYear;
var inputMonth;
var inputDay;
var inputHour;
var inputMinute;
var calendarDisplayTime = false;
var selectBoxHighlightColor = '#D60808'; // Highlight color of select boxes
var selectBoxRolloverBgColor = '#E2EBED'; // Background color on drop down lists(rollover)
var selectBoxMovementInProgress = false;
var activeSelectBox = false;
function cancelCalendarEvent()
{
return false;
}
function isLeapYear(inputYear)
{
if(inputYear%400==0||(inputYear%4==0&&inputYear%100!=0)) return true;
return false;
}
var activeSelectBoxMonth = false;
var activeSelectBoxDirection = false;
function highlightMonthYear()
{
if(activeSelectBoxMonth)activeSelectBoxMonth.className='';
activeSelectBox = this;
if(this.className=='monthYearActive'){
this.className='';
}else{
this.className = 'monthYearActive';
activeSelectBoxMonth = this;
}
if(this.innerHTML.indexOf('-')>=0 || this.innerHTML.indexOf('+')>=0){
if(this.className=='monthYearActive')
selectBoxMovementInProgress = true;
else
selectBoxMovementInProgress = false;
if(this.innerHTML.indexOf('-')>=0)activeSelectBoxDirection = -1; else activeSelectBoxDirection = 1;
}else selectBoxMovementInProgress = false;
}
function showMonthDropDown()
{
if(document.getElementById('monthDropDown').style.display=='block'){
document.getElementById('monthDropDown').style.display='none';
//// fix for EI frame problem on time dropdowns 09/30/2006
EIS_Hide_Frame();
}else{
document.getElementById('monthDropDown').style.display='block';
document.getElementById('yearDropDown').style.display='none';
document.getElementById('hourDropDown').style.display='none';
document.getElementById('minuteDropDown').style.display='none';
if (MSIE)
{ EIS_FIX_EI1('monthDropDown')}
//// fix for EI frame problem on time dropdowns 09/30/2006
}
}
function showYearDropDown()
{
if(document.getElementById('yearDropDown').style.display=='block'){
document.getElementById('yearDropDown').style.display='none';
//// fix for EI frame problem on time dropdowns 09/30/2006
EIS_Hide_Frame();
}else{
document.getElementById('yearDropDown').style.display='block';
document.getElementById('monthDropDown').style.display='none';
document.getElementById('hourDropDown').style.display='none';
document.getElementById('minuteDropDown').style.display='none';
if (MSIE)
{ EIS_FIX_EI1('yearDropDown')}
//// fix for EI frame problem on time dropdowns 09/30/2006
}
}
function showHourDropDown()
{
if(document.getElementById('hourDropDown').style.display=='block'){
document.getElementById('hourDropDown').style.display='none';
//// fix for EI frame problem on time dropdowns 09/30/2006
EIS_Hide_Frame();
}else{
document.getElementById('hourDropDown').style.display='block';
document.getElementById('monthDropDown').style.display='none';
document.getElementById('yearDropDown').style.display='none';
document.getElementById('minuteDropDown').style.display='none';
if (MSIE)
{ EIS_FIX_EI1('hourDropDown')}
//// fix for EI frame problem on time dropdowns 09/30/2006
}
}
function showMinuteDropDown()
{
if(document.getElementById('minuteDropDown').style.display=='block'){
document.getElementById('minuteDropDown').style.display='none';
//// fix for EI frame problem on time dropdowns 09/30/2006
EIS_Hide_Frame();
}else{
document.getElementById('minuteDropDown').style.display='block';
document.getElementById('monthDropDown').style.display='none';
document.getElementById('yearDropDown').style.display='none';
document.getElementById('hourDropDown').style.display='none';
if (MSIE)
{ EIS_FIX_EI1('minuteDropDown')}
//// fix for EI frame problem on time dropdowns 09/30/2006
}
}
function selectMonth()
{
document.getElementById('calendar_month_txt').innerHTML = this.innerHTML
currentMonth = this.id.replace(/[^\d]/g,'');
document.getElementById('monthDropDown').style.display='none';
//// fix for EI frame problem on time dropdowns 09/30/2006
EIS_Hide_Frame();
for(var no=0;no<monthArray.length;no++){
document.getElementById('monthDiv_'+no).style.color='';
}
this.style.color = selectBoxHighlightColor;
activeSelectBoxMonth = this;
writeCalendarContent();
}
function selectHour()
{
document.getElementById('calendar_hour_txt').innerHTML = this.innerHTML
currentHour = this.innerHTML.replace(/[^\d]/g,'');
document.getElementById('hourDropDown').style.display='none';
//// fix for EI frame problem on time dropdowns 09/30/2006
EIS_Hide_Frame();
if(activeSelectBoxHour){
activeSelectBoxHour.style.color='';
}
activeSelectBoxHour=this;
this.style.color = selectBoxHighlightColor;
}
function selectMinute()
{
document.getElementById('calendar_minute_txt').innerHTML = this.innerHTML
currentMinute = this.innerHTML.replace(/[^\d]/g,'');
document.getElementById('minuteDropDown').style.display='none';
//// fix for EI frame problem on time dropdowns 09/30/2006
EIS_Hide_Frame();
if(activeSelectBoxMinute){
activeSelectBoxMinute.style.color='';
}
activeSelectBoxMinute=this;
this.style.color = selectBoxHighlightColor;
}
function selectYear()
{
document.getElementById('calendar_year_txt').innerHTML = this.innerHTML
currentYear = this.innerHTML.replace(/[^\d]/g,'');
document.getElementById('yearDropDown').style.display='none';
//// fix for EI frame problem on time dropdowns 09/30/2006
EIS_Hide_Frame();
if(activeSelectBoxYear){
activeSelectBoxYear.style.color='';
}
activeSelectBoxYear=this;
this.style.color = selectBoxHighlightColor;
writeCalendarContent();
}
function switchMonth()
{
if(this.src.indexOf('left')>=0){
currentMonth=currentMonth-1;;
if(currentMonth<0){
currentMonth=11;
currentYear=currentYear-1;
}
}else{
currentMonth=currentMonth+1;;
if(currentMonth>11){
currentMonth=0;
currentYear=currentYear/1+1;
}
}
writeCalendarContent();
}
function createMonthDiv(){
var div = document.createElement('DIV');
div.className='monthYearPicker';
div.id = 'monthPicker';
for(var no=0;no<monthArray.length;no++){
var subDiv = document.createElement('DIV');
subDiv.innerHTML = monthArray[no];
subDiv.onmouseover = highlightMonthYear;
subDiv.onmouseout = highlightMonthYear;
subDiv.onclick = selectMonth;
subDiv.id = 'monthDiv_' + no;
subDiv.style.width = '56px';
subDiv.onselectstart = cancelCalendarEvent;
div.appendChild(subDiv);
if(currentMonth && currentMonth==no){
subDiv.style.color = selectBoxHighlightColor;
activeSelectBoxMonth = subDiv;
}
}
return div;
}
function changeSelectBoxYear(e,inputObj)
{
if(!inputObj)inputObj =this;
var yearItems = inputObj.parentNode.getElementsByTagName('DIV');
if(inputObj.innerHTML.indexOf('-')>=0){
var startYear = yearItems[1].innerHTML/1 -1;
if(activeSelectBoxYear){
activeSelectBoxYear.style.color='';
}
}else{
var startYear = yearItems[1].innerHTML/1 +1;
if(activeSelectBoxYear){
activeSelectBoxYear.style.color='';
}
}
for(var no=1;no<yearItems.length-1;no++){
yearItems[no].innerHTML = startYear+no-1;
yearItems[no].id = 'yearDiv' + (startYear/1+no/1-1);
}
if(activeSelectBoxYear){
activeSelectBoxYear.style.color='';
if(document.getElementById('yearDiv'+currentYear)){
activeSelectBoxYear = document.getElementById('yearDiv'+currentYear);
activeSelectBoxYear.style.color=selectBoxHighlightColor;;
}
}
}
function changeSelectBoxHour(e,inputObj)
{
if(!inputObj)inputObj = this;
var hourItems = inputObj.parentNode.getElementsByTagName('DIV');
if(inputObj.innerHTML.indexOf('-')>=0){
var startHour = hourItems[1].innerHTML/1 -1;
if(startHour<0)startHour=0;
if(activeSelectBoxHour){
activeSelectBoxHour.style.color='';
}
}else{
var startHour = hourItems[1].innerHTML/1 +1;
if(startHour>14)startHour = 14;
if(activeSelectBoxHour){
activeSelectBoxHour.style.color='';
}
}
var prefix = '';
for(var no=1;no<hourItems.length-1;no++){
if((startHour/1 + no/1) < 11)prefix = '0'; else prefix = '';
hourItems[no].innerHTML = prefix + (startHour+no-1);
hourItems[no].id = 'hourDiv' + (startHour/1+no/1-1);
}
if(activeSelectBoxHour){
activeSelectBoxHour.style.color='';
if(document.getElementById('hourDiv'+currentHour)){
activeSelectBoxHour = document.getElementById('hourDiv'+currentHour);
activeSelectBoxHour.style.color=selectBoxHighlightColor;;
}
}
}
function updateYearDiv()
{
var yearSpan = 5;
if (turnOffYearSpan) {
yearSpan = 0;
}
var div = document.getElementById('yearDropDown');
var yearItems = div.getElementsByTagName('DIV');
for(var no=1;no<yearItems.length-1;no++){
yearItems[no].innerHTML = currentYear/1 -yearSpan + no;
if(currentYear==(currentYear/1 -yearSpan + no)){
yearItems[no].style.color = selectBoxHighlightColor;
activeSelectBoxYear = yearItems[no];
}else{
yearItems[no].style.color = '';
}
}
}
function updateMonthDiv()
{
for(no=0;no<12;no++){
document.getElementById('monthDiv_' + no).style.color = '';
}
document.getElementById('monthDiv_' + currentMonth).style.color = selectBoxHighlightColor;
activeSelectBoxMonth = document.getElementById('monthDiv_' + currentMonth);
}
function updateHourDiv()
{
var div = document.getElementById('hourDropDown');
var hourItems = div.getElementsByTagName('DIV');
var addHours = 0;
if((currentHour/1 -6 + 1)<0){
addHours = (currentHour/1 -6 + 1)*-1;
}
for(var no=1;no<hourItems.length-1;no++){
var prefix='';
if((currentHour/1 -6 + no + addHours) < 10)prefix='0';
hourItems[no].innerHTML = prefix + (currentHour/1 -6 + no + addHours);
if(currentHour==(currentHour/1 -6 + no)){
hourItems[no].style.color = selectBoxHighlightColor;
activeSelectBoxHour = hourItems[no];
}else{
hourItems[no].style.color = '';
}
}
}
function updateMinuteDiv()
{
for(no=0;no<60;no+=intervalSelectBox_minutes){
var prefix = '';
if(no<10)prefix = '0';
document.getElementById('minuteDiv_' + prefix + no).style.color = '';
}
if(document.getElementById('minuteDiv_' + currentMinute)){
document.getElementById('minuteDiv_' + currentMinute).style.color = selectBoxHighlightColor;
activeSelectBoxMinute = document.getElementById('minuteDiv_' + currentMinute);
}
}
function createYearDiv()
{
if(!document.getElementById('yearDropDown')){
var div = document.createElement('DIV');
div.className='monthYearPicker';
}else{
var div = document.getElementById('yearDropDown');
var subDivs = div.getElementsByTagName('DIV');
for(var no=0;no<subDivs.length;no++){
subDivs[no].parentNode.removeChild(subDivs[no]);
}
}
var d = new Date();
if(currentYear){
d.setFullYear(currentYear);
}
var startYear = d.getFullYear()/1 - 5;
var yearSpan = 10;
if (! turnOffYearSpan) {
var subDiv = document.createElement('DIV');
subDiv.innerHTML = ' - ';
subDiv.onclick = changeSelectBoxYear;
subDiv.onmouseover = highlightMonthYear;
subDiv.onmouseout = function(){ selectBoxMovementInProgress = false;};
subDiv.onselectstart = cancelCalendarEvent;
div.appendChild(subDiv);
} else {
startYear = d.getFullYear()/1 - 0;
yearSpan = 2;
}
for(var no=startYear;no<(startYear+yearSpan);no++){
var subDiv = document.createElement('DIV');
subDiv.innerHTML = no;
subDiv.onmouseover = highlightMonthYear;
subDiv.onmouseout = highlightMonthYear;
subDiv.onclick = selectYear;
subDiv.id = 'yearDiv' + no;
subDiv.onselectstart = cancelCalendarEvent;
div.appendChild(subDiv);
if(currentYear && currentYear==no){
subDiv.style.color = selectBoxHighlightColor;
activeSelectBoxYear = subDiv;
}
}
if (! turnOffYearSpan) {
var subDiv = document.createElement('DIV');
subDiv.innerHTML = ' + ';
subDiv.onclick = changeSelectBoxYear;
subDiv.onmouseover = highlightMonthYear;
subDiv.onmouseout = function(){ selectBoxMovementInProgress = false;};
subDiv.onselectstart = cancelCalendarEvent;
div.appendChild(subDiv);
}
return div;
}
/* This function creates the hour div at the bottom bar */
function slideCalendarSelectBox()
{
if(selectBoxMovementInProgress){
if(activeSelectBox.parentNode.id=='hourDropDown'){
changeSelectBoxHour(false,activeSelectBox);
}
if(activeSelectBox.parentNode.id=='yearDropDown'){
changeSelectBoxYear(false,activeSelectBox);
}
}
setTimeout('slideCalendarSelectBox()',speedOfSelectBoxSliding);
}
function createHourDiv()
{
if(!document.getElementById('hourDropDown')){
var div = document.createElement('DIV');
div.className='monthYearPicker';
}else{
var div = document.getElementById('hourDropDown');
var subDivs = div.getElementsByTagName('DIV');
for(var no=0;no<subDivs.length;no++){
subDivs[no].parentNode.removeChild(subDivs[no]);
}
}
if(!currentHour)currentHour=0;
var startHour = currentHour/1;
if(startHour>14)startHour=14;
var subDiv = document.createElement('DIV');
subDiv.innerHTML = ' - ';
subDiv.onclick = changeSelectBoxHour;
subDiv.onmouseover = highlightMonthYear;
subDiv.onmouseout = function(){ selectBoxMovementInProgress = false;};
subDiv.onselectstart = cancelCalendarEvent;
div.appendChild(subDiv);
for(var no=startHour;no<startHour+10;no++){
var prefix = '';
if(no/1<10)prefix='0';
var subDiv = document.createElement('DIV');
subDiv.innerHTML = prefix + no;
subDiv.onmouseover = highlightMonthYear;
subDiv.onmouseout = highlightMonthYear;
subDiv.onclick = selectHour;
subDiv.id = 'hourDiv' + no;
subDiv.onselectstart = cancelCalendarEvent;
div.appendChild(subDiv);
if(currentYear && currentYear==no){
subDiv.style.color = selectBoxHighlightColor;
activeSelectBoxYear = subDiv;
}
}
var subDiv = document.createElement('DIV');
subDiv.innerHTML = ' + ';
subDiv.onclick = changeSelectBoxHour;
subDiv.onmouseover = highlightMonthYear;
subDiv.onmouseout = function(){ selectBoxMovementInProgress = false;};
subDiv.onselectstart = cancelCalendarEvent;
div.appendChild(subDiv);
return div;
}
/* This function creates the minute div at the bottom bar */
function createMinuteDiv()
{
if(!document.getElementById('minuteDropDown')){
var div = document.createElement('DIV');
div.className='monthYearPicker';
}else{
var div = document.getElementById('minuteDropDown');
var subDivs = div.getElementsByTagName('DIV');
for(var no=0;no<subDivs.length;no++){
subDivs[no].parentNode.removeChild(subDivs[no]);
}
}
var startMinute = 0;
var prefix = '';
for(var no=startMinute;no<60;no+=intervalSelectBox_minutes){
if(no<10)prefix='0'; else prefix = '';
var subDiv = document.createElement('DIV');
subDiv.innerHTML = prefix + no;
subDiv.onmouseover = highlightMonthYear;
subDiv.onmouseout = highlightMonthYear;
subDiv.onclick = selectMinute;
subDiv.id = 'minuteDiv_' + prefix + no;
subDiv.onselectstart = cancelCalendarEvent;
div.appendChild(subDiv);
if(currentYear && currentYear==no){
subDiv.style.color = selectBoxHighlightColor;
activeSelectBoxYear = subDiv;
}
}
return div;
}
function highlightSelect()
{
if(this.className=='selectBoxTime'){
this.className = 'selectBoxTimeOver';
this.getElementsByTagName('IMG')[0].src = pathToImages + 'down_time_over.gif';
}else if(this.className=='selectBoxTimeOver'){
this.className = 'selectBoxTime';
this.getElementsByTagName('IMG')[0].src = pathToImages + 'down_time.gif';
}
if(this.className=='selectBox'){
this.className = 'selectBoxOver';
this.getElementsByTagName('IMG')[0].src = pathToImages + 'down_over.gif';
}else if(this.className=='selectBoxOver'){
this.className = 'selectBox';
this.getElementsByTagName('IMG')[0].src = pathToImages + 'down.gif';
}
}
function highlightArrow()
{
if(this.src.indexOf('over')>=0){
if(this.src.indexOf('left')>=0)this.src = pathToImages + 'left.gif';
if(this.src.indexOf('right')>=0)this.src = pathToImages + 'right.gif';
}else{
if(this.src.indexOf('left')>=0)this.src = pathToImages + 'left_over.gif';
if(this.src.indexOf('right')>=0)this.src = pathToImages + 'right_over.gif';
}
}
function highlightClose()
{
if(this.src.indexOf('over')>=0){
this.src = pathToImages + 'close.gif';
}else{
this.src = pathToImages + 'close_over.gif';
}
}
function closeCalendar(){
document.getElementById('yearDropDown').style.display='none';
document.getElementById('monthDropDown').style.display='none';
document.getElementById('hourDropDown').style.display='none';
document.getElementById('minuteDropDown').style.display='none';
calendarDiv.style.display='none';
if(iframeObj){
iframeObj.style.display='none';
//// //// fix for EI frame problem on time dropdowns 09/30/2006
EIS_Hide_Frame();}
if(activeSelectBoxMonth)activeSelectBoxMonth.className='';
if(activeSelectBoxYear)activeSelectBoxYear.className='';
}
function writeTopBar()
{
var topBar = document.createElement('DIV');
topBar.className = 'topBar';
topBar.id = 'topBar';
calendarDiv.appendChild(topBar);
// Left arrow
var leftDiv = document.createElement('DIV');
leftDiv.style.marginRight = '1px';
var img = document.createElement('IMG');
img.src = pathToImages + 'left.gif';
img.onmouseover = highlightArrow;
img.onclick = switchMonth;
img.onmouseout = highlightArrow;
leftDiv.appendChild(img);
topBar.appendChild(leftDiv);
if(Opera)leftDiv.style.width = '16px';
// Right arrow
var rightDiv = document.createElement('DIV');
rightDiv.style.marginRight = '1px';
var img = document.createElement('IMG');
img.src = pathToImages + 'right.gif';
img.onclick = switchMonth;
img.onmouseover = highlightArrow;
img.onmouseout = highlightArrow;
rightDiv.appendChild(img);
if(Opera)rightDiv.style.width = '16px';
topBar.appendChild(rightDiv);
// Month selector
var monthDiv = document.createElement('DIV');
monthDiv.id = 'monthSelect';
monthDiv.onmouseover = highlightSelect;
monthDiv.onmouseout = highlightSelect;
monthDiv.onclick = showMonthDropDown;
var span = document.createElement('SPAN');
span.innerHTML = monthArray[currentMonth];
span.id = 'calendar_month_txt';
monthDiv.appendChild(span);
var img = document.createElement('IMG');
img.src = pathToImages + 'down.gif';
img.style.position = 'absolute';
img.style.right = '0px';
monthDiv.appendChild(img);
monthDiv.className = 'selectBox';
if(Opera){
img.style.cssText = 'float:right;position:relative';
img.style.position = 'relative';
img.style.styleFloat = 'right';
}
topBar.appendChild(monthDiv);
var monthPicker = createMonthDiv();
monthPicker.style.left = '37px';
monthPicker.style.top = monthDiv.offsetTop + monthDiv.offsetHeight + 1 + 'px';
monthPicker.style.width ='60px';
monthPicker.id = 'monthDropDown';
calendarDiv.appendChild(monthPicker);
// Year selector
var yearDiv = document.createElement('DIV');
yearDiv.onmouseover = highlightSelect;
yearDiv.onmouseout = highlightSelect;
yearDiv.onclick = showYearDropDown;
var span = document.createElement('SPAN');
span.innerHTML = currentYear;
span.id = 'calendar_year_txt';
yearDiv.appendChild(span);
topBar.appendChild(yearDiv);
var img = document.createElement('IMG');
img.src = pathToImages + 'down.gif';
yearDiv.appendChild(img);
yearDiv.className = 'selectBox';
if(Opera){
yearDiv.style.width = '50px';
img.style.cssText = 'float:right';
img.style.position = 'relative';
img.style.styleFloat = 'right';
}
var yearPicker = createYearDiv();
yearPicker.style.left = '113px';
yearPicker.style.top = monthDiv.offsetTop + monthDiv.offsetHeight + 1 + 'px';
yearPicker.style.width = '35px';
yearPicker.id = 'yearDropDown';
calendarDiv.appendChild(yearPicker);
var img = document.createElement('IMG');
img.src = pathToImages + 'close.gif';
img.style.styleFloat = 'right';
img.onmouseover = highlightClose;
img.onmouseout = highlightClose;
img.onclick = closeCalendar;
topBar.appendChild(img);
if(!document.all){
img.style.position = 'absolute';
img.style.right = '2px';
}
}
function writeCalendarContent()
{
var calendarContentDivExists = true;
if(!calendarContentDiv){
calendarContentDiv = document.createElement('DIV');
calendarDiv.appendChild(calendarContentDiv);
calendarContentDivExists = false;
}
currentMonth = currentMonth/1;
var d = new Date();
d.setFullYear(currentYear);
d.setDate(1);
d.setMonth(currentMonth);
var dayStartOfMonth = d.getDay();
if (! weekStartsOnSunday) {
if(dayStartOfMonth==0)dayStartOfMonth=7;
dayStartOfMonth--;
}
document.getElementById('calendar_year_txt').innerHTML = currentYear;
document.getElementById('calendar_month_txt').innerHTML = monthArray[currentMonth];
document.getElementById('calendar_hour_txt').innerHTML = currentHour/1 > 9 ? currentHour : '0' + currentHour;
document.getElementById('calendar_minute_txt').innerHTML = currentMinute/1 >9 ? currentMinute : '0' + currentMinute;
var existingTable = calendarContentDiv.getElementsByTagName('TABLE');
if(existingTable.length>0){
calendarContentDiv.removeChild(existingTable[0]);
}
var calTable = document.createElement('TABLE');
calTable.width = '100%';
calTable.cellSpacing = '0';
calendarContentDiv.appendChild(calTable);
var calTBody = document.createElement('TBODY');
calTable.appendChild(calTBody);
var row = calTBody.insertRow(-1);
row.className = 'calendar_week_row';
if (showWeekNumber) {
var cell = row.insertCell(-1);
cell.innerHTML = weekString;
cell.className = 'calendar_week_column';
cell.style.backgroundColor = selectBoxRolloverBgColor;
}
for(var no=0;no<dayArray.length;no++){
var cell = row.insertCell(-1);
cell.innerHTML = dayArray[no];
}
var row = calTBody.insertRow(-1);
if (showWeekNumber) {
var cell = row.insertCell(-1);
cell.className = 'calendar_week_column';
cell.style.backgroundColor = selectBoxRolloverBgColor;
var week = getWeek(currentYear,currentMonth,1);
cell.innerHTML = week; // Week
}
for(var no=0;no<dayStartOfMonth;no++){
var cell = row.insertCell(-1);
cell.innerHTML = ' ';
}
var colCounter = dayStartOfMonth;
var daysInMonth = daysInMonthArray[currentMonth];
if(daysInMonth==28){
if(isLeapYear(currentYear))daysInMonth=29;
}
for(var no=1;no<=daysInMonth;no++){
d.setDate(no-1);
if(colCounter>0 && colCounter%7==0){
var row = calTBody.insertRow(-1);
if (showWeekNumber) {
var cell = row.insertCell(-1);
cell.className = 'calendar_week_column';
var week = getWeek(currentYear,currentMonth,no);
cell.innerHTML = week; // Week
cell.style.backgroundColor = selectBoxRolloverBgColor;
}
}
var cell = row.insertCell(-1);
if(currentYear==inputYear && currentMonth == inputMonth && no==inputDay){
cell.className='activeDay';
}
cell.innerHTML = no;
cell.onclick = pickDate;
colCounter++;
}
if(!document.all){
if(calendarContentDiv.offsetHeight)
document.getElementById('topBar').style.top = calendarContentDiv.offsetHeight + document.getElementById('timeBar').offsetHeight + document.getElementById('topBar').offsetHeight -1 + 'px';
else{
document.getElementById('topBar').style.top = '';
document.getElementById('topBar').style.bottom = '0px';
}
}
if(iframeObj){
if(!calendarContentDivExists)setTimeout('resizeIframe()',350);else setTimeout('resizeIframe()',10);
}
}
function resizeIframe()
{
iframeObj.style.width = calendarDiv.offsetWidth + 'px';
iframeObj.style.height = calendarDiv.offsetHeight + 'px' ;
}
function pickTodaysDate()
{
var d = new Date();
currentMonth = d.getMonth();
currentYear = d.getFullYear();
pickDate(false,d.getDate());
}
function pickDate(e,inputDay)
{
var month = currentMonth/1 +1;
if(month<10)month = '0' + month;
var day;
if(!inputDay && this)day = this.innerHTML; else day = inputDay;
if(day/1<10)day = '0' + day;
if(returnFormat){
returnFormat = returnFormat.replace('dd',day);
returnFormat = returnFormat.replace('mm',month);
returnFormat = returnFormat.replace('yyyy',currentYear);
returnFormat = returnFormat.replace('hh',currentHour);
returnFormat = returnFormat.replace('ii',currentMinute);
returnFormat = returnFormat.replace('d',day/1);
returnFormat = returnFormat.replace('m',month/1);
returnDateTo.value = returnFormat;
try{
returnDateTo.onchange();
}catch(e){
}
}else{
for(var no=0;no<returnDateToYear.options.length;no++){
if(returnDateToYear.options[no].value==currentYear){
returnDateToYear.selectedIndex=no;
break;
}
}
for(var no=0;no<returnDateToMonth.options.length;no++){
if(returnDateToMonth.options[no].value==parseFloat(month)){
returnDateToMonth.selectedIndex=no;
break;
}
}
for(var no=0;no<returnDateToDay.options.length;no++){
if(returnDateToDay.options[no].value==parseFloat(day)){
returnDateToDay.selectedIndex=no;
break;
}
}
if(calendarDisplayTime){
for(var no=0;no<returnDateToHour.options.length;no++){
if(returnDateToHour.options[no].value==parseFloat(currentHour)){
returnDateToHour.selectedIndex=no;
break;
}
}
for(var no=0;no<returnDateToMinute.options.length;no++){
if(returnDateToMinute.options[no].value==parseFloat(currentMinute)){
returnDateToMinute.selectedIndex=no;
break;
}
}
}
}
closeCalendar();
}
// This function is from http://www.codeproject.com/csharp/gregorianwknum.asp
// Only changed the month add
function getWeek(year,month,day){
if (! weekStartsOnSunday) {
day = (day/1);
} else {
day = (day/1)+1;
}
year = year /1;
month = month/1 + 1; //use 1-12
var a = Math.floor((14-(month))/12);
var y = year+4800-a;
var m = (month)+(12*a)-3;
var jd = day + Math.floor(((153*m)+2)/5) +
(365*y) + Math.floor(y/4) - Math.floor(y/100) +
Math.floor(y/400) - 32045; // (gregorian calendar)
var d4 = (jd+31741-(jd%7))%146097%36524%1461;
var L = Math.floor(d4/1460);
var d1 = ((d4-L)%365)+L;
NumberOfWeek = Math.floor(d1/7) + 1;
return NumberOfWeek;
}
function writeTimeBar()
{
var timeBar = document.createElement('DIV');
timeBar.id = 'timeBar';
timeBar.className = 'timeBar';
var subDiv = document.createElement('DIV');
subDiv.innerHTML = 'Time:';
// hour selector
var hourDiv = document.createElement('DIV');
hourDiv.onmouseover = highlightSelect;
hourDiv.onmouseout = highlightSelect;
hourDiv.onclick = showHourDropDown;
hourDiv.style.width = '30px';
var span = document.createElement('SPAN');
span.innerHTML = currentHour;
span.id = 'calendar_hour_txt';
hourDiv.appendChild(span);
timeBar.appendChild(hourDiv);
var img = document.createElement('IMG');
img.src = pathToImages + 'down_time.gif';
hourDiv.appendChild(img);
hourDiv.className = 'selectBoxTime';
if(Opera){
hourDiv.style.width = '30px';
img.style.cssText = 'float:right';
img.style.position = 'relative';
img.style.styleFloat = 'right';
}
var hourPicker = createHourDiv();
hourPicker.style.left = '130px';
//hourPicker.style.top = monthDiv.offsetTop + monthDiv.offsetHeight + 1 + 'px';
hourPicker.style.width = '35px';
hourPicker.id = 'hourDropDown';
calendarDiv.appendChild(hourPicker);
// Add Minute picker
// Year selector
var minuteDiv = document.createElement('DIV');
minuteDiv.onmouseover = highlightSelect;
minuteDiv.onmouseout = highlightSelect;
minuteDiv.onclick = showMinuteDropDown;
minuteDiv.style.width = '30px';
var span = document.createElement('SPAN');
span.innerHTML = currentMinute;
span.id = 'calendar_minute_txt';
minuteDiv.appendChild(span);
timeBar.appendChild(minuteDiv);
var img = document.createElement('IMG');
img.src = pathToImages + 'down_time.gif';
minuteDiv.appendChild(img);
minuteDiv.className = 'selectBoxTime';
if(Opera){
minuteDiv.style.width = '30px';
img.style.cssText = 'float:right';
img.style.position = 'relative';
img.style.styleFloat = 'right';
}
var minutePicker = createMinuteDiv();
minutePicker.style.left = '167px';
//minutePicker.style.top = monthDiv.offsetTop + monthDiv.offsetHeight + 1 + 'px';
minutePicker.style.width = '35px';
minutePicker.id = 'minuteDropDown';
calendarDiv.appendChild(minutePicker);
return timeBar;
}
function writeBottomBar()
{
var d = new Date();
var bottomBar = document.createElement('DIV');
bottomBar.id = 'bottomBar';
bottomBar.style.cursor = 'pointer';
bottomBar.className = 'todaysDate';
// var todayStringFormat = '[todayString] [dayString] [day] [monthString] [year]'; ;;
var subDiv = document.createElement('DIV');
subDiv.onclick = pickTodaysDate;
subDiv.id = 'todaysDateString';
subDiv.style.width = (calendarDiv.offsetWidth - 95) + 'px';
var day = d.getDay();
if (! weekStartsOnSunday) {
if(day==0)day = 7;
day--;
}
var bottomString = todayStringFormat;
bottomString = bottomString.replace('[monthString]',monthArrayShort[d.getMonth()]);
bottomString = bottomString.replace('[day]',d.getDate());
bottomString = bottomString.replace('[year]',d.getFullYear());
bottomString = bottomString.replace('[dayString]',dayArray[day].toLowerCase());
bottomString = bottomString.replace('[UCFdayString]',dayArray[day]);
bottomString = bottomString.replace('[todayString]',todayString);
subDiv.innerHTML = todayString + ': ' + d.getDate() + '. ' + monthArrayShort[d.getMonth()] + ', ' + d.getFullYear() ;
subDiv.innerHTML = bottomString ;
bottomBar.appendChild(subDiv);
var timeDiv = writeTimeBar();
bottomBar.appendChild(timeDiv);
calendarDiv.appendChild(bottomBar);
}
function getTopPos(inputObj)
{
var returnValue = inputObj.offsetTop + inputObj.offsetHeight;
while((inputObj = inputObj.offsetParent) != null)returnValue += inputObj.offsetTop;
return returnValue + calendar_offsetTop;
}
function getleftPos(inputObj)
{
var returnValue = inputObj.offsetLeft;
while((inputObj = inputObj.offsetParent) != null)returnValue += inputObj.offsetLeft;
return returnValue + calendar_offsetLeft;
}
function positionCalendar(inputObj)
{
calendarDiv.style.left = getleftPos(inputObj) + 'px';
calendarDiv.style.top = getTopPos(inputObj) + 'px';
if(iframeObj){
iframeObj.style.left = calendarDiv.style.left;
iframeObj.style.top = calendarDiv.style.top;
//// fix for EI frame problem on time dropdowns 09/30/2006
iframeObj2.style.left = calendarDiv.style.left;
iframeObj2.style.top = calendarDiv.style.top;
}
}
function initCalendar()
{
if(MSIE){
iframeObj = document.createElement('IFRAME');
iframeObj.style.filter = 'alpha(opacity=0)';
iframeObj.style.position = 'absolute';
iframeObj.border='0px';
iframeObj.style.border = '0px';
iframeObj.style.backgroundColor = '#FF0000';
//// fix for EI frame problem on time dropdowns 09/30/2006
iframeObj2 = document.createElement('IFRAME');
iframeObj2.style.position = 'absolute';
iframeObj2.border='0px';
iframeObj2.style.border = '0px';
iframeObj2.style.height = '1px';
iframeObj2.style.width = '1px';
//// fix for EI frame problem on time dropdowns 09/30/2006
// Added fixed for HTTPS
iframeObj2.src = 'blank.html';
iframeObj.src = 'blank.html';
document.body.appendChild(iframeObj2); // gfb move this down AFTER the .src is set
document.body.appendChild(iframeObj);
}
calendarDiv = document.createElement('DIV');
calendarDiv.id = 'calendarDiv';
calendarDiv.style.zIndex = 1000;
slideCalendarSelectBox();
document.body.appendChild(calendarDiv);
writeBottomBar();
writeTopBar();
if(!currentYear){
var d = new Date();
currentMonth = d.getMonth();
currentYear = d.getFullYear();
}
writeCalendarContent();
}
function setTimeProperties()
{
if(!calendarDisplayTime){
document.getElementById('timeBar').style.display='none';
document.getElementById('timeBar').style.visibility='hidden';
document.getElementById('todaysDateString').style.width = '100%';
}else{
document.getElementById('timeBar').style.display='block';
document.getElementById('timeBar').style.visibility='visible';
document.getElementById('hourDropDown').style.top = document.getElementById('calendar_minute_txt').parentNode.offsetHeight + calendarContentDiv.offsetHeight + document.getElementById('topBar').offsetHeight + 'px';
document.getElementById('minuteDropDown').style.top = document.getElementById('calendar_minute_txt').parentNode.offsetHeight + calendarContentDiv.offsetHeight + document.getElementById('topBar').offsetHeight + 'px';
document.getElementById('minuteDropDown').style.right = '50px';
document.getElementById('hourDropDown').style.right = '50px';
document.getElementById('todaysDateString').style.width = '115px';
}
}
function calendarSortItems(a,b)
{
return a/1 - b/1;
}
function displayCalendar(inputField,format,buttonObj,displayTime,timeInput)
{
if(displayTime)calendarDisplayTime=true; else calendarDisplayTime = false;
if(inputField.value.length>6){ //dates must have at least 6 digits...
if(!inputField.value.match(/^[0-9]*?$/gi)){
var items = inputField.value.split(/[^0-9]/gi);
var positionArray = new Object();
positionArray.m = format.indexOf('mm');
if(positionArray.m==-1)positionArray.m = format.indexOf('m');
positionArray.d = format.indexOf('dd');
if(positionArray.d==-1)positionArray.d = format.indexOf('d');
positionArray.y = format.indexOf('yyyy');
positionArray.h = format.indexOf('hh');
positionArray.i = format.indexOf('ii');
this.initialHour = '00';
this.initialMinute = '00';
var elements = ['y','m','d','h','i'];
var properties = ['currentYear','currentMonth','inputDay','currentHour','currentMinute'];
var propertyLength = [4,2,2,2,2];
for(var i=0;i<elements.length;i++) {
if(positionArray[elements[i]]>=0) {
window[properties[i]] = inputField.value.substr(positionArray[elements[i]],propertyLength[i])/1;
}
}
currentMonth--;
}else{
var monthPos = format.indexOf('mm');
currentMonth = inputField.value.substr(monthPos,2)/1 -1;
var yearPos = format.indexOf('yyyy');
currentYear = inputField.value.substr(yearPos,4);
var dayPos = format.indexOf('dd');
tmpDay = inputField.value.substr(dayPos,2);
var hourPos = format.indexOf('hh');
if(hourPos>=0){
tmpHour = inputField.value.substr(hourPos,2);
currentHour = tmpHour;
if(currentHour.length==1) currentHour = '0'
}else{
currentHour = '00';
}
var minutePos = format.indexOf('ii');
if(minutePos>=0){
tmpMinute = inputField.value.substr(minutePos,2);
currentMinute = tmpMinute;
}else{
currentMinute = '00';
}
}
}else{
var d = new Date();
currentMonth = d.getMonth();
currentYear = d.getFullYear();
currentHour = '08';
currentMinute = '00';
inputDay = d.getDate()/1;
}
inputYear = currentYear;
inputMonth = currentMonth;
if(!calendarDiv){
initCalendar();
}else{
if(calendarDiv.style.display=='block'){
closeCalendar();
return false;
}
writeCalendarContent();
}
returnFormat = format;
returnDateTo = inputField;
positionCalendar(buttonObj);
calendarDiv.style.visibility = 'visible';
calendarDiv.style.display = 'block';
if(iframeObj){
iframeObj.style.display = '';
iframeObj.style.height = '140px';
iframeObj.style.width = '195px';
iframeObj2.style.display = '';
iframeObj2.style.height = '140px';
iframeObj2.style.width = '195px';
}
setTimeProperties();
updateYearDiv();
updateMonthDiv();
updateMinuteDiv();
updateHourDiv();
}
function displayCalendarSelectBox(yearInput,monthInput,dayInput,hourInput,minuteInput,buttonObj)
{
if(!hourInput)calendarDisplayTime=false; else calendarDisplayTime = true;
currentMonth = monthInput.options[monthInput.selectedIndex].value/1-1;
currentYear = yearInput.options[yearInput.selectedIndex].value;
if(hourInput){
currentHour = hourInput.options[hourInput.selectedIndex].value;
inputHour = currentHour/1;
}
if(minuteInput){
currentMinute = minuteInput.options[minuteInput.selectedIndex].value;
inputMinute = currentMinute/1;
}
inputYear = yearInput.options[yearInput.selectedIndex].value;
inputMonth = monthInput.options[monthInput.selectedIndex].value/1 - 1;
inputDay = dayInput.options[dayInput.selectedIndex].value/1;
if(!calendarDiv){
initCalendar();
}else{
writeCalendarContent();
}
returnDateToYear = yearInput;
returnDateToMonth = monthInput;
returnDateToDay = dayInput;
returnDateToHour = hourInput;
returnDateToMinute = minuteInput;
returnFormat = false;
returnDateTo = false;
positionCalendar(buttonObj);
calendarDiv.style.visibility = 'visible';
calendarDiv.style.display = 'block';
if(iframeObj){
iframeObj.style.display = '';
iframeObj.style.height = calendarDiv.offsetHeight + 'px';
iframeObj.style.width = calendarDiv.offsetWidth + 'px';
//// fix for EI frame problem on time dropdowns 09/30/2006
iframeObj2.style.display = '';
iframeObj2.style.height = calendarDiv.offsetHeight + 'px';
iframeObj2.style.width = calendarDiv.offsetWidth + 'px'
}
setTimeProperties();
updateYearDiv();
updateMonthDiv();
updateHourDiv();
updateMinuteDiv();
}
| JavaScript |
/*
Copyright (c) 2003-2011, CKSource - Frederico Knabben. All rights reserved.
For licensing, see LICENSE.html or http://ckeditor.com/license
*/
CKEDITOR.skins.add( 'kama', (function()
{
var uiColorStylesheetId = 'cke_ui_color';
return {
editor : { css : [ 'editor.css' ] },
dialog : { css : [ 'dialog.css' ] },
richcombo : { canGroup: false },
templates : { css : [ 'templates.css' ] },
margins : [ 0, 0, 0, 0 ],
init : function( editor )
{
if ( editor.config.width && !isNaN( editor.config.width ) )
editor.config.width -= 12;
var uiColorMenus = [];
var uiColorRegex = /\$color/g;
var uiColorMenuCss = "/* UI Color Support */\
.cke_skin_kama .cke_menuitem .cke_icon_wrapper\
{\
background-color: $color !important;\
border-color: $color !important;\
}\
\
.cke_skin_kama .cke_menuitem a:hover .cke_icon_wrapper,\
.cke_skin_kama .cke_menuitem a:focus .cke_icon_wrapper,\
.cke_skin_kama .cke_menuitem a:active .cke_icon_wrapper\
{\
background-color: $color !important;\
border-color: $color !important;\
}\
\
.cke_skin_kama .cke_menuitem a:hover .cke_label,\
.cke_skin_kama .cke_menuitem a:focus .cke_label,\
.cke_skin_kama .cke_menuitem a:active .cke_label\
{\
background-color: $color !important;\
}\
\
.cke_skin_kama .cke_menuitem a.cke_disabled:hover .cke_label,\
.cke_skin_kama .cke_menuitem a.cke_disabled:focus .cke_label,\
.cke_skin_kama .cke_menuitem a.cke_disabled:active .cke_label\
{\
background-color: transparent !important;\
}\
\
.cke_skin_kama .cke_menuitem a.cke_disabled:hover .cke_icon_wrapper,\
.cke_skin_kama .cke_menuitem a.cke_disabled:focus .cke_icon_wrapper,\
.cke_skin_kama .cke_menuitem a.cke_disabled:active .cke_icon_wrapper\
{\
background-color: $color !important;\
border-color: $color !important;\
}\
\
.cke_skin_kama .cke_menuitem a.cke_disabled .cke_icon_wrapper\
{\
background-color: $color !important;\
border-color: $color !important;\
}\
\
.cke_skin_kama .cke_menuseparator\
{\
background-color: $color !important;\
}\
\
.cke_skin_kama .cke_menuitem a:hover,\
.cke_skin_kama .cke_menuitem a:focus,\
.cke_skin_kama .cke_menuitem a:active\
{\
background-color: $color !important;\
}";
// We have to split CSS declarations for webkit.
if ( CKEDITOR.env.webkit )
{
uiColorMenuCss = uiColorMenuCss.split( '}' ).slice( 0, -1 );
for ( var i = 0 ; i < uiColorMenuCss.length ; i++ )
uiColorMenuCss[ i ] = uiColorMenuCss[ i ].split( '{' );
}
function getStylesheet( document )
{
var node = document.getById( uiColorStylesheetId );
if ( !node )
{
node = document.getHead().append( 'style' );
node.setAttribute( "id", uiColorStylesheetId );
node.setAttribute( "type", "text/css" );
}
return node;
}
function updateStylesheets( styleNodes, styleContent, replace )
{
var r, i, content;
for ( var id = 0 ; id < styleNodes.length ; id++ )
{
if ( CKEDITOR.env.webkit )
{
for ( i = 0 ; i < styleContent.length ; i++ )
{
content = styleContent[ i ][ 1 ];
for ( r = 0 ; r < replace.length ; r++ )
content = content.replace( replace[ r ][ 0 ], replace[ r ][ 1 ] );
styleNodes[ id ].$.sheet.addRule( styleContent[ i ][ 0 ], content );
}
}
else
{
content = styleContent;
for ( r = 0 ; r < replace.length ; r++ )
content = content.replace( replace[ r ][ 0 ], replace[ r ][ 1 ] );
if ( CKEDITOR.env.ie )
styleNodes[ id ].$.styleSheet.cssText += content;
else
styleNodes[ id ].$.innerHTML += content;
}
}
}
var uiColorRegexp = /\$color/g;
CKEDITOR.tools.extend( editor,
{
uiColor: null,
getUiColor : function()
{
return this.uiColor;
},
setUiColor : function( color )
{
var cssContent,
uiStyle = getStylesheet( CKEDITOR.document ),
cssId = '.' + editor.id;
var cssSelectors =
[
cssId + " .cke_wrapper",
cssId + "_dialog .cke_dialog_contents",
cssId + "_dialog a.cke_dialog_tab",
cssId + "_dialog .cke_dialog_footer"
].join( ',' );
var cssProperties = "background-color: $color !important;";
if ( CKEDITOR.env.webkit )
cssContent = [ [ cssSelectors, cssProperties ] ];
else
cssContent = cssSelectors + '{' + cssProperties + '}';
return ( this.setUiColor =
function( color )
{
var replace = [ [ uiColorRegexp, color ] ];
editor.uiColor = color;
// Update general style.
updateStylesheets( [ uiStyle ], cssContent, replace );
// Update menu styles.
updateStylesheets( uiColorMenus, uiColorMenuCss, replace );
})( color );
}
});
editor.on( 'menuShow', function( event )
{
var panel = event.data[ 0 ];
var iframe = panel.element.getElementsByTag( 'iframe' ).getItem( 0 ).getFrameDocument();
// Add stylesheet if missing.
if ( !iframe.getById( 'cke_ui_color' ) )
{
var node = getStylesheet( iframe );
uiColorMenus.push( node );
var color = editor.getUiColor();
// Set uiColor for new menu.
if ( color )
updateStylesheets( [ node ], uiColorMenuCss, [ [ uiColorRegexp, color ] ] );
}
});
// Apply UI color if specified in config.
if ( editor.config.uiColor )
editor.setUiColor( editor.config.uiColor );
}
};
})() );
(function()
{
CKEDITOR.dialog ? dialogSetup() : CKEDITOR.on( 'dialogPluginReady', dialogSetup );
function dialogSetup()
{
CKEDITOR.dialog.on( 'resize', function( evt )
{
var data = evt.data,
width = data.width,
height = data.height,
dialog = data.dialog,
contents = dialog.parts.contents;
if ( data.skin != 'kama' )
return;
contents.setStyles(
{
width : width + 'px',
height : height + 'px'
});
});
}
})();
/**
* The base user interface color to be used by the editor. Not all skins are
* compatible with this setting.
* @name CKEDITOR.config.uiColor
* @type String
* @default '' (empty)
* @example
* // Using a color code.
* config.uiColor = '#AADC6E';
* @example
* // Using an HTML color name.
* config.uiColor = 'Gold';
*/
| JavaScript |
/*
Copyright (c) 2003-2011, CKSource - Frederico Knabben. All rights reserved.
For licensing, see LICENSE.html or http://ckeditor.com/license
*/
CKEDITOR.skins.add( 'v2', (function()
{
return {
editor : { css : [ 'editor.css' ] },
dialog : { css : [ 'dialog.css' ] },
separator : { canGroup: false },
templates : { css : [ 'templates.css' ] },
margins : [ 0, 14, 18, 14 ]
};
})() );
(function()
{
CKEDITOR.dialog ? dialogSetup() : CKEDITOR.on( 'dialogPluginReady', dialogSetup );
function dialogSetup()
{
CKEDITOR.dialog.on( 'resize', function( evt )
{
var data = evt.data,
width = data.width,
height = data.height,
dialog = data.dialog,
contents = dialog.parts.contents;
if ( data.skin != 'v2' )
return;
contents.setStyles(
{
width : width + 'px',
height : height + 'px'
});
if ( !CKEDITOR.env.ie || CKEDITOR.env.ie9Compat )
return;
// Fix the size of the elements which have flexible lengths.
setTimeout( function()
{
var innerDialog = dialog.parts.dialog.getChild( [ 0, 0, 0 ] ),
body = innerDialog.getChild( 0 ),
bodyWidth = body.getSize( 'width' );
height += body.getChild( 0 ).getSize( 'height' ) + 1;
// tc
var el = innerDialog.getChild( 2 );
el.setSize( 'width', bodyWidth );
// bc
el = innerDialog.getChild( 7 );
el.setSize( 'width', bodyWidth - 28 );
// ml
el = innerDialog.getChild( 4 );
el.setSize( 'height', height );
// mr
el = innerDialog.getChild( 5 );
el.setSize( 'height', height );
},
100 );
});
}
})();
| JavaScript |
/*
Copyright (c) 2003-2011, CKSource - Frederico Knabben. All rights reserved.
For licensing, see LICENSE.html or http://ckeditor.com/license
*/
CKEDITOR.skins.add( 'office2003', (function()
{
return {
editor : { css : [ 'editor.css' ] },
dialog : { css : [ 'dialog.css' ] },
separator : { canGroup: false },
templates : { css : [ 'templates.css' ] },
margins : [ 0, 14, 18, 14 ]
};
})() );
(function()
{
CKEDITOR.dialog ? dialogSetup() : CKEDITOR.on( 'dialogPluginReady', dialogSetup );
function dialogSetup()
{
CKEDITOR.dialog.on( 'resize', function( evt )
{
var data = evt.data,
width = data.width,
height = data.height,
dialog = data.dialog,
contents = dialog.parts.contents;
if ( data.skin != 'office2003' )
return;
contents.setStyles(
{
width : width + 'px',
height : height + 'px'
});
if ( !CKEDITOR.env.ie || CKEDITOR.env.ie9Compat )
return;
// Fix the size of the elements which have flexible lengths.
var fixSize = function()
{
var innerDialog = dialog.parts.dialog.getChild( [ 0, 0, 0 ] ),
body = innerDialog.getChild( 0 ),
bodyWidth = body.getSize( 'width' );
height += body.getChild( 0 ).getSize( 'height' ) + 1;
// tc
var el = innerDialog.getChild( 2 );
el.setSize( 'width', bodyWidth );
// bc
el = innerDialog.getChild( 7 );
el.setSize( 'width', bodyWidth - 28 );
// ml
el = innerDialog.getChild( 4 );
el.setSize( 'height', height );
// mr
el = innerDialog.getChild( 5 );
el.setSize( 'height', height );
};
setTimeout( fixSize, 100 );
// Ensure size is correct for RTL mode. (#4003)
if ( evt.editor.lang.dir == 'rtl' )
setTimeout( fixSize, 1000 );
});
}
})();
| JavaScript |
/*
Copyright (c) 2003-2011, CKSource - Frederico Knabben. All rights reserved.
For licensing, see LICENSE.html or http://ckeditor.com/license
*/
/**
* @fileOverview Contains the second part of the {@link CKEDITOR} object
* definition, which defines the basic editor features to be available in
* the root ckeditor_basic.js file.
*/
if ( CKEDITOR.status == 'unloaded' )
{
(function()
{
CKEDITOR.event.implementOn( CKEDITOR );
/**
* Forces the full CKEditor core code, in the case only the basic code has been
* loaded (ckeditor_basic.js). This method self-destroys (becomes undefined) in
* the first call or as soon as the full code is available.
* @example
* // Check if the full core code has been loaded and load it.
* if ( CKEDITOR.loadFullCore )
* <b>CKEDITOR.loadFullCore()</b>;
*/
CKEDITOR.loadFullCore = function()
{
// If not the basic code is not ready it, just mark it to be loaded.
if ( CKEDITOR.status != 'basic_ready' )
{
CKEDITOR.loadFullCore._load = 1;
return;
}
// Destroy this function.
delete CKEDITOR.loadFullCore;
// Append the script to the head.
var script = document.createElement( 'script' );
script.type = 'text/javascript';
script.src = CKEDITOR.basePath + 'ckeditor.js';
document.getElementsByTagName( 'head' )[0].appendChild( script );
};
/**
* The time to wait (in seconds) to load the full editor code after the
* page load, if the "ckeditor_basic" file is used. If set to zero, the
* editor is loaded on demand, as soon as an instance is created.
*
* This value must be set on the page before the page load completion.
* @type Number
* @default 0 (zero)
* @example
* // Loads the full source after five seconds.
* CKEDITOR.loadFullCoreTimeout = 5;
*/
CKEDITOR.loadFullCoreTimeout = 0;
/**
* The class name used to identify <textarea> elements to be replace
* by CKEditor instances.
* @type String
* @default 'ckeditor'
* @example
* <b>CKEDITOR.replaceClass</b> = 'rich_editor';
*/
CKEDITOR.replaceClass = 'ckeditor';
/**
* Enables the replacement of all textareas with class name matching
* {@link CKEDITOR.replaceClass}.
* @type Boolean
* @default true
* @example
* // Disable the auto-replace feature.
* <b>CKEDITOR.replaceByClassEnabled</b> = false;
*/
CKEDITOR.replaceByClassEnabled = 1;
var createInstance = function( elementOrIdOrName, config, creationFunction, data )
{
if ( CKEDITOR.env.isCompatible )
{
// Load the full core.
if ( CKEDITOR.loadFullCore )
CKEDITOR.loadFullCore();
var editor = creationFunction( elementOrIdOrName, config, data );
CKEDITOR.add( editor );
return editor;
}
return null;
};
/**
* Replaces a <textarea> or a DOM element (DIV) with a CKEditor
* instance. For textareas, the initial value in the editor will be the
* textarea value. For DOM elements, their innerHTML will be used
* instead. We recommend using TEXTAREA and DIV elements only.
* @param {Object|String} elementOrIdOrName The DOM element (textarea), its
* ID or name.
* @param {Object} [config] The specific configurations to apply to this
* editor instance. Configurations set here will override global CKEditor
* settings.
* @returns {CKEDITOR.editor} The editor instance created.
* @example
* <textarea id="myfield" name="myfield"><:/textarea>
* ...
* <b>CKEDITOR.replace( 'myfield' )</b>;
* @example
* var textarea = document.body.appendChild( document.createElement( 'textarea' ) );
* <b>CKEDITOR.replace( textarea )</b>;
*/
CKEDITOR.replace = function( elementOrIdOrName, config )
{
return createInstance( elementOrIdOrName, config, CKEDITOR.editor.replace );
};
/**
* Creates a new editor instance inside a specific DOM element.
* @param {Object|String} elementOrId The DOM element or its ID.
* @param {Object} [config] The specific configurations to apply to this
* editor instance. Configurations set here will override global CKEditor
* settings.
* @param {String} [data] Since 3.3. Initial value for the instance.
* @returns {CKEDITOR.editor} The editor instance created.
* @example
* <div id="editorSpace"><:/div>
* ...
* <b>CKEDITOR.appendTo( 'editorSpace' )</b>;
*/
CKEDITOR.appendTo = function( elementOrId, config, data )
{
return createInstance( elementOrId, config, CKEDITOR.editor.appendTo, data );
};
// Documented at ckeditor.js.
CKEDITOR.add = function( editor )
{
// For now, just put the editor in the pending list. It will be
// processed as soon as the full code gets loaded.
var pending = this._.pending || ( this._.pending = [] );
pending.push( editor );
};
/**
* Replace all <textarea> elements available in the document with
* editor instances.
* @example
* // Replace all <textarea> elements in the page.
* CKEDITOR.replaceAll();
* @example
* // Replace all <textarea class="myClassName"> elements in the page.
* CKEDITOR.replaceAll( 'myClassName' );
* @example
* // Selectively replace <textarea> elements, based on custom assertions.
* CKEDITOR.replaceAll( function( textarea, config )
* {
* // Custom code to evaluate the replace, returning false
* // if it must not be done.
* // It also passes the "config" parameter, so the
* // developer can customize the instance.
* } );
*/
CKEDITOR.replaceAll = function()
{
var textareas = document.getElementsByTagName( 'textarea' );
for ( var i = 0 ; i < textareas.length ; i++ )
{
var config = null,
textarea = textareas[i];
// The "name" and/or "id" attribute must exist.
if ( !textarea.name && !textarea.id )
continue;
if ( typeof arguments[0] == 'string' )
{
// The textarea class name could be passed as the function
// parameter.
var classRegex = new RegExp( '(?:^|\\s)' + arguments[0] + '(?:$|\\s)' );
if ( !classRegex.test( textarea.className ) )
continue;
}
else if ( typeof arguments[0] == 'function' )
{
// An assertion function could be passed as the function parameter.
// It must explicitly return "false" to ignore a specific <textarea>.
config = {};
if ( arguments[0]( textarea, config ) === false )
continue;
}
this.replace( textarea, config );
}
};
(function()
{
var onload = function()
{
var loadFullCore = CKEDITOR.loadFullCore,
loadFullCoreTimeout = CKEDITOR.loadFullCoreTimeout;
// Replace all textareas with the default class name.
if ( CKEDITOR.replaceByClassEnabled )
CKEDITOR.replaceAll( CKEDITOR.replaceClass );
CKEDITOR.status = 'basic_ready';
if ( loadFullCore && loadFullCore._load )
loadFullCore();
else if ( loadFullCoreTimeout )
{
setTimeout( function()
{
if ( CKEDITOR.loadFullCore )
CKEDITOR.loadFullCore();
}
, loadFullCoreTimeout * 1000 );
}
};
if ( window.addEventListener )
window.addEventListener( 'load', onload, false );
else if ( window.attachEvent )
window.attachEvent( 'onload', onload );
})();
CKEDITOR.status = 'basic_loaded';
})();
}
| JavaScript |
/*
Copyright (c) 2003-2011, CKSource - Frederico Knabben. All rights reserved.
For licensing, see LICENSE.html or http://ckeditor.com/license
*/
/**
* @fileOverview Defines the {@link CKEDITOR.dtd} object, which holds the DTD
* mapping for XHTML 1.0 Transitional. This file was automatically
* generated from the file: xhtml1-transitional.dtd.
*/
/**
* @namespace Holds and object representation of the HTML DTD to be used by the
* editor in its internal operations.<br />
* <br />
* Each element in the DTD is represented by a property in this object. Each
* property contains the list of elements that can be contained by the element.
* Text is represented by the "#" property.<br />
* <br />
* Several special grouping properties are also available. Their names start
* with the "$" character.
* @example
* // Check if "div" can be contained in a "p" element.
* alert( !!CKEDITOR.dtd[ 'p' ][ 'div' ] ); "false"
* @example
* // Check if "p" can be contained in a "div" element.
* alert( !!CKEDITOR.dtd[ 'div' ][ 'p' ] ); "true"
* @example
* // Check if "p" is a block element.
* alert( !!CKEDITOR.dtd.$block[ 'p' ] ); "true"
*/
CKEDITOR.dtd = (function()
{
var X = CKEDITOR.tools.extend,
A = {isindex:1,fieldset:1},
B = {input:1,button:1,select:1,textarea:1,label:1},
C = X({a:1},B),
D = X({iframe:1},C),
E = {hr:1,ul:1,menu:1,div:1,section:1,header:1,footer:1,nav:1,article:1,aside:1,figure:1,dialog:1,hgroup:1,mark:1,time:1,meter:1,command:1,keygen:1,output:1,progress:1,audio:1,video:1,details:1,datagrid:1,datalist:1,blockquote:1,noscript:1,table:1,center:1,address:1,dir:1,pre:1,h5:1,dl:1,h4:1,noframes:1,h6:1,ol:1,h1:1,h3:1,h2:1},
F = {ins:1,del:1,script:1,style:1},
G = X({b:1,acronym:1,bdo:1,'var':1,'#':1,abbr:1,code:1,br:1,i:1,cite:1,kbd:1,u:1,strike:1,s:1,tt:1,strong:1,q:1,samp:1,em:1,dfn:1,span:1,wbr:1},F),
H = X({sub:1,img:1,object:1,sup:1,basefont:1,map:1,applet:1,font:1,big:1,small:1,mark:1},G),
I = X({p:1},H),
J = X({iframe:1},H,B),
K = {img:1,noscript:1,br:1,kbd:1,center:1,button:1,basefont:1,h5:1,h4:1,samp:1,h6:1,ol:1,h1:1,h3:1,h2:1,form:1,font:1,'#':1,select:1,menu:1,ins:1,abbr:1,label:1,code:1,table:1,script:1,cite:1,input:1,iframe:1,strong:1,textarea:1,noframes:1,big:1,small:1,span:1,hr:1,sub:1,bdo:1,'var':1,div:1,section:1,header:1,footer:1,nav:1,article:1,aside:1,figure:1,dialog:1,hgroup:1,mark:1,time:1,meter:1,menu:1,command:1,keygen:1,output:1,progress:1,audio:1,video:1,details:1,datagrid:1,datalist:1,object:1,sup:1,strike:1,dir:1,map:1,dl:1,applet:1,del:1,isindex:1,fieldset:1,ul:1,b:1,acronym:1,a:1,blockquote:1,i:1,u:1,s:1,tt:1,address:1,q:1,pre:1,p:1,em:1,dfn:1},
L = X({a:1},J),
M = {tr:1},
N = {'#':1},
O = X({param:1},K),
P = X({form:1},A,D,E,I),
Q = {li:1},
R = {style:1,script:1},
S = {base:1,link:1,meta:1,title:1},
T = X(S,R),
U = {head:1,body:1},
V = {html:1};
var block = {address:1,blockquote:1,center:1,dir:1,div:1,section:1,header:1,footer:1,nav:1,article:1,aside:1,figure:1,dialog:1,hgroup:1,time:1,meter:1,menu:1,command:1,keygen:1,output:1,progress:1,audio:1,video:1,details:1,datagrid:1,datalist:1,dl:1,fieldset:1,form:1,h1:1,h2:1,h3:1,h4:1,h5:1,h6:1,hr:1,isindex:1,noframes:1,ol:1,p:1,pre:1,table:1,ul:1};
return /** @lends CKEDITOR.dtd */ {
// The "$" items have been added manually.
// List of elements living outside body.
$nonBodyContent: X(V,U,S),
/**
* List of block elements, like "p" or "div".
* @type Object
* @example
*/
$block : block,
/**
* List of block limit elements.
* @type Object
* @example
*/
$blockLimit : { body:1,div:1,section:1,header:1,footer:1,nav:1,article:1,aside:1,figure:1,dialog:1,hgroup:1,time:1,meter:1,menu:1,command:1,keygen:1,output:1,progress:1,audio:1,video:1,details:1,datagrid:1,datalist:1,td:1,th:1,caption:1,form:1 },
/**
* List of inline (<span> like) elements.
*/
$inline : L, // Just like span.
/**
* list of elements that can be children at <body>.
*/
$body : X({script:1,style:1}, block),
$cdata : {script:1,style:1},
/**
* List of empty (self-closing) elements, like "br" or "img".
* @type Object
* @example
*/
$empty : {area:1,base:1,br:1,col:1,hr:1,img:1,input:1,link:1,meta:1,param:1,wbr:1},
/**
* List of list item elements, like "li" or "dd".
* @type Object
* @example
*/
$listItem : {dd:1,dt:1,li:1},
/**
* List of list root elements.
* @type Object
* @example
*/
$list: {ul:1,ol:1,dl:1},
/**
* Elements that accept text nodes, but are not possible to edit into
* the browser.
* @type Object
* @example
*/
$nonEditable : {applet:1,button:1,embed:1,iframe:1,map:1,object:1,option:1,script:1,textarea:1,param:1,audio:1,video:1},
/**
* List of block tags with each one a singleton element lives in the corresponding structure for description.
*/
$captionBlock : { caption:1, legend:1 },
/**
* List of elements that can be ignored if empty, like "b" or "span".
* @type Object
* @example
*/
$removeEmpty : {abbr:1,acronym:1,address:1,b:1,bdo:1,big:1,cite:1,code:1,del:1,dfn:1,em:1,font:1,i:1,ins:1,label:1,kbd:1,q:1,s:1,samp:1,small:1,span:1,strike:1,strong:1,sub:1,sup:1,tt:1,u:1,'var':1,mark:1},
/**
* List of elements that have tabindex set to zero by default.
* @type Object
* @example
*/
$tabIndex : {a:1,area:1,button:1,input:1,object:1,select:1,textarea:1},
/**
* List of elements used inside the "table" element, like "tbody" or "td".
* @type Object
* @example
*/
$tableContent : {caption:1,col:1,colgroup:1,tbody:1,td:1,tfoot:1,th:1,thead:1,tr:1},
html: U,
head: T,
style: N,
script: N,
body: P,
base: {},
link: {},
meta: {},
title: N,
col : {},
tr : {td:1,th:1},
img : {},
colgroup : {col:1},
noscript : P,
td : P,
br : {},
wbr : {},
th : P,
center : P,
kbd : L,
button : X(I,E),
basefont : {},
h5 : L,
h4 : L,
samp : L,
h6 : L,
ol : Q,
h1 : L,
h3 : L,
option : N,
h2 : L,
form : X(A,D,E,I),
select : {optgroup:1,option:1},
font : L,
ins : L,
menu : Q,
abbr : L,
label : L,
table : {thead:1,col:1,tbody:1,tr:1,colgroup:1,caption:1,tfoot:1},
code : L,
tfoot : M,
cite : L,
li : P,
input : {},
iframe : P,
strong : L,
textarea : N,
noframes : P,
big : L,
small : L,
span : L,
hr : {},
dt : L,
sub : L,
optgroup : {option:1},
param : {},
bdo : L,
'var' : L,
div : P,
object : O,
sup : L,
dd : P,
strike : L,
area : {},
dir : Q,
map : X({area:1,form:1,p:1},A,F,E),
applet : O,
dl : {dt:1,dd:1},
del : L,
isindex : {},
fieldset : X({legend:1},K),
thead : M,
ul : Q,
acronym : L,
b : L,
a : J,
blockquote : P,
caption : L,
i : L,
u : L,
tbody : M,
s : L,
address : X(D,I),
tt : L,
legend : L,
q : L,
pre : X(G,C),
p : L,
em : L,
dfn : L,
//HTML5
section : P,
header : P,
footer : P,
nav : P,
article : P,
aside : P,
figure: P,
dialog : P,
hgroup : P,
mark : L,
time : L,
meter : L,
menu : L,
command : L,
keygen : L,
output : L,
progress : O,
audio : O,
video : O,
details : O,
datagrid : O,
datalist : O
};
})();
// PACKAGER_RENAME( CKEDITOR.dtd )
| JavaScript |
/*
Copyright (c) 2003-2011, CKSource - Frederico Knabben. All rights reserved.
For licensing, see LICENSE.html or http://ckeditor.com/license
*/
/**
* Creates a {@link CKEDITOR.htmlParser} class instance.
* @class Provides an "event like" system to parse strings of HTML data.
* @example
* var parser = new CKEDITOR.htmlParser();
* parser.onTagOpen = function( tagName, attributes, selfClosing )
* {
* alert( tagName );
* };
* parser.parse( '<p>Some <b>text</b>.</p>' );
*/
CKEDITOR.htmlParser = function()
{
this._ =
{
htmlPartsRegex : new RegExp( '<(?:(?:\\/([^>]+)>)|(?:!--([\\S|\\s]*?)-->)|(?:([^\\s>]+)\\s*((?:(?:"[^"]*")|(?:\'[^\']*\')|[^"\'>])*)\\/?>))', 'g' )
};
};
(function()
{
var attribsRegex = /([\w\-:.]+)(?:(?:\s*=\s*(?:(?:"([^"]*)")|(?:'([^']*)')|([^\s>]+)))|(?=\s|$))/g,
emptyAttribs = {checked:1,compact:1,declare:1,defer:1,disabled:1,ismap:1,multiple:1,nohref:1,noresize:1,noshade:1,nowrap:1,readonly:1,selected:1};
CKEDITOR.htmlParser.prototype =
{
/**
* Function to be fired when a tag opener is found. This function
* should be overriden when using this class.
* @param {String} tagName The tag name. The name is guarantted to be
* lowercased.
* @param {Object} attributes An object containing all tag attributes. Each
* property in this object represent and attribute name and its
* value is the attribute value.
* @param {Boolean} selfClosing true if the tag closes itself, false if the
* tag doesn't.
* @example
* var parser = new CKEDITOR.htmlParser();
* parser.onTagOpen = function( tagName, attributes, selfClosing )
* {
* alert( tagName ); // e.g. "b"
* });
* parser.parse( "<!-- Example --><b>Hello</b>" );
*/
onTagOpen : function() {},
/**
* Function to be fired when a tag closer is found. This function
* should be overriden when using this class.
* @param {String} tagName The tag name. The name is guarantted to be
* lowercased.
* @example
* var parser = new CKEDITOR.htmlParser();
* parser.onTagClose = function( tagName )
* {
* alert( tagName ); // e.g. "b"
* });
* parser.parse( "<!-- Example --><b>Hello</b>" );
*/
onTagClose : function() {},
/**
* Function to be fired when text is found. This function
* should be overriden when using this class.
* @param {String} text The text found.
* @example
* var parser = new CKEDITOR.htmlParser();
* parser.onText = function( text )
* {
* alert( text ); // e.g. "Hello"
* });
* parser.parse( "<!-- Example --><b>Hello</b>" );
*/
onText : function() {},
/**
* Function to be fired when CDATA section is found. This function
* should be overriden when using this class.
* @param {String} cdata The CDATA been found.
* @example
* var parser = new CKEDITOR.htmlParser();
* parser.onCDATA = function( cdata )
* {
* alert( cdata ); // e.g. "var hello;"
* });
* parser.parse( "<script>var hello;</script>" );
*/
onCDATA : function() {},
/**
* Function to be fired when a commend is found. This function
* should be overriden when using this class.
* @param {String} comment The comment text.
* @example
* var parser = new CKEDITOR.htmlParser();
* parser.onComment = function( comment )
* {
* alert( comment ); // e.g. " Example "
* });
* parser.parse( "<!-- Example --><b>Hello</b>" );
*/
onComment : function() {},
/**
* Parses text, looking for HTML tokens, like tag openers or closers,
* or comments. This function fires the onTagOpen, onTagClose, onText
* and onComment function during its execution.
* @param {String} html The HTML to be parsed.
* @example
* var parser = new CKEDITOR.htmlParser();
* // The onTagOpen, onTagClose, onText and onComment should be overriden
* // at this point.
* parser.parse( "<!-- Example --><b>Hello</b>" );
*/
parse : function( html )
{
var parts,
tagName,
nextIndex = 0,
cdata; // The collected data inside a CDATA section.
while ( ( parts = this._.htmlPartsRegex.exec( html ) ) )
{
var tagIndex = parts.index;
if ( tagIndex > nextIndex )
{
var text = html.substring( nextIndex, tagIndex );
if ( cdata )
cdata.push( text );
else
this.onText( text );
}
nextIndex = this._.htmlPartsRegex.lastIndex;
/*
"parts" is an array with the following items:
0 : The entire match for opening/closing tags and comments.
1 : Group filled with the tag name for closing tags.
2 : Group filled with the comment text.
3 : Group filled with the tag name for opening tags.
4 : Group filled with the attributes part of opening tags.
*/
// Closing tag
if ( ( tagName = parts[ 1 ] ) )
{
tagName = tagName.toLowerCase();
if ( cdata && CKEDITOR.dtd.$cdata[ tagName ] )
{
// Send the CDATA data.
this.onCDATA( cdata.join('') );
cdata = null;
}
if ( !cdata )
{
this.onTagClose( tagName );
continue;
}
}
// If CDATA is enabled, just save the raw match.
if ( cdata )
{
cdata.push( parts[ 0 ] );
continue;
}
// Opening tag
if ( ( tagName = parts[ 3 ] ) )
{
tagName = tagName.toLowerCase();
// There are some tag names that can break things, so let's
// simply ignore them when parsing. (#5224)
if ( /="/.test( tagName ) )
continue;
var attribs = {},
attribMatch,
attribsPart = parts[ 4 ],
selfClosing = !!( attribsPart && attribsPart.charAt( attribsPart.length - 1 ) == '/' );
if ( attribsPart )
{
while ( ( attribMatch = attribsRegex.exec( attribsPart ) ) )
{
var attName = attribMatch[1].toLowerCase(),
attValue = attribMatch[2] || attribMatch[3] || attribMatch[4] || '';
if ( !attValue && emptyAttribs[ attName ] )
attribs[ attName ] = attName;
else
attribs[ attName ] = attValue;
}
}
this.onTagOpen( tagName, attribs, selfClosing );
// Open CDATA mode when finding the appropriate tags.
if ( !cdata && CKEDITOR.dtd.$cdata[ tagName ] )
cdata = [];
continue;
}
// Comment
if ( ( tagName = parts[ 2 ] ) )
this.onComment( tagName );
}
if ( html.length > nextIndex )
this.onText( html.substring( nextIndex, html.length ) );
}
};
})();
| JavaScript |
/*
Copyright (c) 2003-2011, CKSource - Frederico Knabben. All rights reserved.
For licensing, see LICENSE.html or http://ckeditor.com/license
*/
/**
* @fileOverview Defines the {@link CKEDITOR.resourceManager} class, which is
* the base for resource managers, like plugins and themes.
*/
/**
* Base class for resource managers, like plugins and themes. This class is not
* intended to be used out of the CKEditor core code.
* @param {String} basePath The path for the resources folder.
* @param {String} fileName The name used for resource files.
* @namespace
* @example
*/
CKEDITOR.resourceManager = function( basePath, fileName )
{
/**
* The base directory containing all resources.
* @name CKEDITOR.resourceManager.prototype.basePath
* @type String
* @example
*/
this.basePath = basePath;
/**
* The name used for resource files.
* @name CKEDITOR.resourceManager.prototype.fileName
* @type String
* @example
*/
this.fileName = fileName;
/**
* Contains references to all resources that have already been registered
* with {@link #add}.
* @name CKEDITOR.resourceManager.prototype.registered
* @type Object
* @example
*/
this.registered = {};
/**
* Contains references to all resources that have already been loaded
* with {@link #load}.
* @name CKEDITOR.resourceManager.prototype.loaded
* @type Object
* @example
*/
this.loaded = {};
/**
* Contains references to all resources that have already been registered
* with {@link #addExternal}.
* @name CKEDITOR.resourceManager.prototype.externals
* @type Object
* @example
*/
this.externals = {};
/**
* @private
*/
this._ =
{
// List of callbacks waiting for plugins to be loaded.
waitingList : {}
};
};
CKEDITOR.resourceManager.prototype =
{
/**
* Registers a resource.
* @param {String} name The resource name.
* @param {Object} [definition] The resource definition.
* @example
* CKEDITOR.plugins.add( 'sample', { ... plugin definition ... } );
* @see CKEDITOR.pluginDefinition
*/
add : function( name, definition )
{
if ( this.registered[ name ] )
throw '[CKEDITOR.resourceManager.add] The resource name "' + name + '" is already registered.';
CKEDITOR.fire( name + CKEDITOR.tools.capitalize( this.fileName ) + 'Ready',
this.registered[ name ] = definition || {} );
},
/**
* Gets the definition of a specific resource.
* @param {String} name The resource name.
* @type Object
* @example
* var definition = <b>CKEDITOR.plugins.get( 'sample' )</b>;
*/
get : function( name )
{
return this.registered[ name ] || null;
},
/**
* Get the folder path for a specific loaded resource.
* @param {String} name The resource name.
* @type String
* @example
* alert( <b>CKEDITOR.plugins.getPath( 'sample' )</b> ); // "<editor path>/plugins/sample/"
*/
getPath : function( name )
{
var external = this.externals[ name ];
return CKEDITOR.getUrl( ( external && external.dir ) || this.basePath + name + '/' );
},
/**
* Get the file path for a specific loaded resource.
* @param {String} name The resource name.
* @type String
* @example
* alert( <b>CKEDITOR.plugins.getFilePath( 'sample' )</b> ); // "<editor path>/plugins/sample/plugin.js"
*/
getFilePath : function( name )
{
var external = this.externals[ name ];
return CKEDITOR.getUrl(
this.getPath( name ) +
( ( external && ( typeof external.file == 'string' ) ) ? external.file : this.fileName + '.js' ) );
},
/**
* Registers one or more resources to be loaded from an external path
* instead of the core base path.
* @param {String} names The resource names, separated by commas.
* @param {String} path The path of the folder containing the resource.
* @param {String} [fileName] The resource file name. If not provided, the
* default name is used; If provided with a empty string, will implicitly indicates that {@param path}
* is already the full path.
* @example
* // Loads a plugin from '/myplugin/samples/plugin.js'.
* CKEDITOR.plugins.addExternal( 'sample', '/myplugins/sample/' );
* @example
* // Loads a plugin from '/myplugin/samples/my_plugin.js'.
* CKEDITOR.plugins.addExternal( 'sample', '/myplugins/sample/', 'my_plugin.js' );
* @example
* // Loads a plugin from '/myplugin/samples/my_plugin.js'.
* CKEDITOR.plugins.addExternal( 'sample', '/myplugins/sample/my_plugin.js', '' );
*/
addExternal : function( names, path, fileName )
{
names = names.split( ',' );
for ( var i = 0 ; i < names.length ; i++ )
{
var name = names[ i ];
this.externals[ name ] =
{
dir : path,
file : fileName
};
}
},
/**
* Loads one or more resources.
* @param {String|Array} name The name of the resource to load. It may be a
* string with a single resource name, or an array with several names.
* @param {Function} callback A function to be called when all resources
* are loaded. The callback will receive an array containing all
* loaded names.
* @param {Object} [scope] The scope object to be used for the callback
* call.
* @example
* <b>CKEDITOR.plugins.load</b>( 'myplugin', function( plugins )
* {
* alert( plugins['myplugin'] ); // "object"
* });
*/
load : function( names, callback, scope )
{
// Ensure that we have an array of names.
if ( !CKEDITOR.tools.isArray( names ) )
names = names ? [ names ] : [];
var loaded = this.loaded,
registered = this.registered,
urls = [],
urlsNames = {},
resources = {};
// Loop through all names.
for ( var i = 0 ; i < names.length ; i++ )
{
var name = names[ i ];
if ( !name )
continue;
// If not available yet.
if ( !loaded[ name ] && !registered[ name ] )
{
var url = this.getFilePath( name );
urls.push( url );
if ( !( url in urlsNames ) )
urlsNames[ url ] = [];
urlsNames[ url ].push( name );
}
else
resources[ name ] = this.get( name );
}
CKEDITOR.scriptLoader.load( urls, function( completed, failed )
{
if ( failed.length )
{
throw '[CKEDITOR.resourceManager.load] Resource name "' + urlsNames[ failed[ 0 ] ].join( ',' )
+ '" was not found at "' + failed[ 0 ] + '".';
}
for ( var i = 0 ; i < completed.length ; i++ )
{
var nameList = urlsNames[ completed[ i ] ];
for ( var j = 0 ; j < nameList.length ; j++ )
{
var name = nameList[ j ];
resources[ name ] = this.get( name );
loaded[ name ] = 1;
}
}
callback.call( scope, resources );
}
, this);
}
};
| JavaScript |
/*
Copyright (c) 2003-2011, CKSource - Frederico Knabben. All rights reserved.
For licensing, see LICENSE.html or http://ckeditor.com/license
*/
/**
* @fileOverview Defines the {@link CKEDITOR.event} class, which serves as the
* base for classes and objects that require event handling features.
*/
if ( !CKEDITOR.event )
{
/**
* Creates an event class instance. This constructor is rearely used, being
* the {@link #.implementOn} function used in class prototypes directly
* instead.
* @class This is a base class for classes and objects that require event
* handling features.<br />
* <br />
* Do not confuse this class with {@link CKEDITOR.dom.event} which is
* instead used for DOM events. The CKEDITOR.event class implements the
* internal event system used by the CKEditor to fire API related events.
* @example
*/
CKEDITOR.event = function()
{};
/**
* Implements the {@link CKEDITOR.event} features in an object.
* @param {Object} targetObject The object into which implement the features.
* @example
* var myObject = { message : 'Example' };
* <b>CKEDITOR.event.implementOn( myObject }</b>;
* myObject.on( 'testEvent', function()
* {
* alert( this.message ); // "Example"
* });
* myObject.fire( 'testEvent' );
*/
CKEDITOR.event.implementOn = function( targetObject )
{
var eventProto = CKEDITOR.event.prototype;
for ( var prop in eventProto )
{
if ( targetObject[ prop ] == undefined )
targetObject[ prop ] = eventProto[ prop ];
}
};
CKEDITOR.event.prototype = (function()
{
// Returns the private events object for a given object.
var getPrivate = function( obj )
{
var _ = ( obj.getPrivate && obj.getPrivate() ) || obj._ || ( obj._ = {} );
return _.events || ( _.events = {} );
};
var eventEntry = function( eventName )
{
this.name = eventName;
this.listeners = [];
};
eventEntry.prototype =
{
// Get the listener index for a specified function.
// Returns -1 if not found.
getListenerIndex : function( listenerFunction )
{
for ( var i = 0, listeners = this.listeners ; i < listeners.length ; i++ )
{
if ( listeners[i].fn == listenerFunction )
return i;
}
return -1;
}
};
return /** @lends CKEDITOR.event.prototype */ {
/**
* Registers a listener to a specific event in the current object.
* @param {String} eventName The event name to which listen.
* @param {Function} listenerFunction The function listening to the
* event. A single {@link CKEDITOR.eventInfo} object instanced
* is passed to this function containing all the event data.
* @param {Object} [scopeObj] The object used to scope the listener
* call (the this object. If omitted, the current object is used.
* @param {Object} [listenerData] Data to be sent as the
* {@link CKEDITOR.eventInfo#listenerData} when calling the
* listener.
* @param {Number} [priority] The listener priority. Lower priority
* listeners are called first. Listeners with the same priority
* value are called in registration order. Defaults to 10.
* @example
* someObject.on( 'someEvent', function()
* {
* alert( this == someObject ); // "true"
* });
* @example
* someObject.on( 'someEvent', function()
* {
* alert( this == anotherObject ); // "true"
* }
* , anotherObject );
* @example
* someObject.on( 'someEvent', function( event )
* {
* alert( event.listenerData ); // "Example"
* }
* , null, 'Example' );
* @example
* someObject.on( 'someEvent', function() { ... } ); // 2nd called
* someObject.on( 'someEvent', function() { ... }, null, null, 100 ); // 3rd called
* someObject.on( 'someEvent', function() { ... }, null, null, 1 ); // 1st called
*/
on : function( eventName, listenerFunction, scopeObj, listenerData, priority )
{
// Get the event entry (create it if needed).
var events = getPrivate( this ),
event = events[ eventName ] || ( events[ eventName ] = new eventEntry( eventName ) );
if ( event.getListenerIndex( listenerFunction ) < 0 )
{
// Get the listeners.
var listeners = event.listeners;
// Fill the scope.
if ( !scopeObj )
scopeObj = this;
// Default the priority, if needed.
if ( isNaN( priority ) )
priority = 10;
var me = this;
// Create the function to be fired for this listener.
var listenerFirer = function( editor, publisherData, stopFn, cancelFn )
{
var ev =
{
name : eventName,
sender : this,
editor : editor,
data : publisherData,
listenerData : listenerData,
stop : stopFn,
cancel : cancelFn,
removeListener : function()
{
me.removeListener( eventName, listenerFunction );
}
};
listenerFunction.call( scopeObj, ev );
return ev.data;
};
listenerFirer.fn = listenerFunction;
listenerFirer.priority = priority;
// Search for the right position for this new listener, based on its
// priority.
for ( var i = listeners.length - 1 ; i >= 0 ; i-- )
{
// Find the item which should be before the new one.
if ( listeners[ i ].priority <= priority )
{
// Insert the listener in the array.
listeners.splice( i + 1, 0, listenerFirer );
return;
}
}
// If no position has been found (or zero length), put it in
// the front of list.
listeners.unshift( listenerFirer );
}
},
/**
* Fires an specific event in the object. All registered listeners are
* called at this point.
* @function
* @param {String} eventName The event name to fire.
* @param {Object} [data] Data to be sent as the
* {@link CKEDITOR.eventInfo#data} when calling the
* listeners.
* @param {CKEDITOR.editor} [editor] The editor instance to send as the
* {@link CKEDITOR.eventInfo#editor} when calling the
* listener.
* @returns {Boolean|Object} A booloan indicating that the event is to be
* canceled, or data returned by one of the listeners.
* @example
* someObject.on( 'someEvent', function() { ... } );
* someObject.on( 'someEvent', function() { ... } );
* <b>someObject.fire( 'someEvent' )</b>; // both listeners are called
* @example
* someObject.on( 'someEvent', function( event )
* {
* alert( event.data ); // "Example"
* });
* <b>someObject.fire( 'someEvent', 'Example' )</b>;
*/
fire : (function()
{
// Create the function that marks the event as stopped.
var stopped = false;
var stopEvent = function()
{
stopped = true;
};
// Create the function that marks the event as canceled.
var canceled = false;
var cancelEvent = function()
{
canceled = true;
};
return function( eventName, data, editor )
{
// Get the event entry.
var event = getPrivate( this )[ eventName ];
// Save the previous stopped and cancelled states. We may
// be nesting fire() calls.
var previousStopped = stopped,
previousCancelled = canceled;
// Reset the stopped and canceled flags.
stopped = canceled = false;
if ( event )
{
var listeners = event.listeners;
if ( listeners.length )
{
// As some listeners may remove themselves from the
// event, the original array length is dinamic. So,
// let's make a copy of all listeners, so we are
// sure we'll call all of them.
listeners = listeners.slice( 0 );
// Loop through all listeners.
for ( var i = 0 ; i < listeners.length ; i++ )
{
// Call the listener, passing the event data.
var retData = listeners[i].call( this, editor, data, stopEvent, cancelEvent );
if ( typeof retData != 'undefined' )
data = retData;
// No further calls is stopped or canceled.
if ( stopped || canceled )
break;
}
}
}
var ret = canceled || ( typeof data == 'undefined' ? false : data );
// Restore the previous stopped and canceled states.
stopped = previousStopped;
canceled = previousCancelled;
return ret;
};
})(),
/**
* Fires an specific event in the object, releasing all listeners
* registered to that event. The same listeners are not called again on
* successive calls of it or of {@link #fire}.
* @param {String} eventName The event name to fire.
* @param {Object} [data] Data to be sent as the
* {@link CKEDITOR.eventInfo#data} when calling the
* listeners.
* @param {CKEDITOR.editor} [editor] The editor instance to send as the
* {@link CKEDITOR.eventInfo#editor} when calling the
* listener.
* @returns {Boolean|Object} A booloan indicating that the event is to be
* canceled, or data returned by one of the listeners.
* @example
* someObject.on( 'someEvent', function() { ... } );
* someObject.fire( 'someEvent' ); // above listener called
* <b>someObject.fireOnce( 'someEvent' )</b>; // above listener called
* someObject.fire( 'someEvent' ); // no listeners called
*/
fireOnce : function( eventName, data, editor )
{
var ret = this.fire( eventName, data, editor );
delete getPrivate( this )[ eventName ];
return ret;
},
/**
* Unregisters a listener function from being called at the specified
* event. No errors are thrown if the listener has not been
* registered previously.
* @param {String} eventName The event name.
* @param {Function} listenerFunction The listener function to unregister.
* @example
* var myListener = function() { ... };
* someObject.on( 'someEvent', myListener );
* someObject.fire( 'someEvent' ); // myListener called
* <b>someObject.removeListener( 'someEvent', myListener )</b>;
* someObject.fire( 'someEvent' ); // myListener not called
*/
removeListener : function( eventName, listenerFunction )
{
// Get the event entry.
var event = getPrivate( this )[ eventName ];
if ( event )
{
var index = event.getListenerIndex( listenerFunction );
if ( index >= 0 )
event.listeners.splice( index, 1 );
}
},
/**
* Checks if there is any listener registered to a given event.
* @param {String} eventName The event name.
* @example
* var myListener = function() { ... };
* someObject.on( 'someEvent', myListener );
* alert( someObject.<b>hasListeners( 'someEvent' )</b> ); // "true"
* alert( someObject.<b>hasListeners( 'noEvent' )</b> ); // "false"
*/
hasListeners : function( eventName )
{
var event = getPrivate( this )[ eventName ];
return ( event && event.listeners.length > 0 ) ;
}
};
})();
}
| JavaScript |
/*
Copyright (c) 2003-2011, CKSource - Frederico Knabben. All rights reserved.
For licensing, see LICENSE.html or http://ckeditor.com/license
*/
/**
* @fileOverview Defines the {@link CKEDITOR.scriptLoader} object, used to load scripts
* asynchronously.
*/
/**
* Load scripts asynchronously.
* @namespace
* @example
*/
CKEDITOR.scriptLoader = (function()
{
var uniqueScripts = {},
waitingList = {};
return /** @lends CKEDITOR.scriptLoader */ {
/**
* Loads one or more external script checking if not already loaded
* previously by this function.
* @param {String|Array} scriptUrl One or more URLs pointing to the
* scripts to be loaded.
* @param {Function} [callback] A function to be called when the script
* is loaded and executed. If a string is passed to "scriptUrl", a
* boolean parameter is passed to the callback, indicating the
* success of the load. If an array is passed instead, two array
* parameters are passed to the callback; the first contains the
* URLs that have been properly loaded, and the second the failed
* ones.
* @param {Object} [scope] The scope ("this" reference) to be used for
* the callback call. Default to {@link CKEDITOR}.
* @param {Boolean} [showBusy] Changes the cursor of the document while
+ * the script is loaded.
* @example
* CKEDITOR.scriptLoader.load( '/myscript.js' );
* @example
* CKEDITOR.scriptLoader.load( '/myscript.js', function( success )
* {
* // Alerts "true" if the script has been properly loaded.
* // HTTP error 404 should return "false".
* alert( success );
* });
* @example
* CKEDITOR.scriptLoader.load( [ '/myscript1.js', '/myscript2.js' ], function( completed, failed )
* {
* alert( 'Number of scripts loaded: ' + completed.length );
* alert( 'Number of failures: ' + failed.length );
* });
*/
load : function( scriptUrl, callback, scope, showBusy )
{
var isString = ( typeof scriptUrl == 'string' );
if ( isString )
scriptUrl = [ scriptUrl ];
if ( !scope )
scope = CKEDITOR;
var scriptCount = scriptUrl.length,
completed = [],
failed = [];
var doCallback = function( success )
{
if ( callback )
{
if ( isString )
callback.call( scope, success );
else
callback.call( scope, completed, failed );
}
};
if ( scriptCount === 0 )
{
doCallback( true );
return;
}
var checkLoaded = function( url, success )
{
( success ? completed : failed ).push( url );
if ( --scriptCount <= 0 )
{
showBusy && CKEDITOR.document.getDocumentElement().removeStyle( 'cursor' );
doCallback( success );
}
};
var onLoad = function( url, success )
{
// Mark this script as loaded.
uniqueScripts[ url ] = 1;
// Get the list of callback checks waiting for this file.
var waitingInfo = waitingList[ url ];
delete waitingList[ url ];
// Check all callbacks waiting for this file.
for ( var i = 0 ; i < waitingInfo.length ; i++ )
waitingInfo[ i ]( url, success );
};
var loadScript = function( url )
{
if ( uniqueScripts[ url ] )
{
checkLoaded( url, true );
return;
}
var waitingInfo = waitingList[ url ] || ( waitingList[ url ] = [] );
waitingInfo.push( checkLoaded );
// Load it only for the first request.
if ( waitingInfo.length > 1 )
return;
// Create the <script> element.
var script = new CKEDITOR.dom.element( 'script' );
script.setAttributes( {
type : 'text/javascript',
src : url } );
if ( callback )
{
if ( CKEDITOR.env.ie )
{
// FIXME: For IE, we are not able to return false on error (like 404).
/** @ignore */
script.$.onreadystatechange = function ()
{
if ( script.$.readyState == 'loaded' || script.$.readyState == 'complete' )
{
script.$.onreadystatechange = null;
onLoad( url, true );
}
};
}
else
{
/** @ignore */
script.$.onload = function()
{
// Some browsers, such as Safari, may call the onLoad function
// immediately. Which will break the loading sequence. (#3661)
setTimeout( function() { onLoad( url, true ); }, 0 );
};
// FIXME: Opera and Safari will not fire onerror.
/** @ignore */
script.$.onerror = function()
{
onLoad( url, false );
};
}
}
// Append it to <head>.
script.appendTo( CKEDITOR.document.getHead() );
CKEDITOR.fire( 'download', url ); // @Packager.RemoveLine
};
showBusy && CKEDITOR.document.getDocumentElement().setStyle( 'cursor', 'wait' );
for ( var i = 0 ; i < scriptCount ; i++ )
{
loadScript( scriptUrl[ i ] );
}
}
};
})();
| JavaScript |
/*
Copyright (c) 2003-2011, CKSource - Frederico Knabben. All rights reserved.
For licensing, see LICENSE.html or http://ckeditor.com/license
*/
/**
* Contains UI features related to an editor instance.
* @constructor
* @param {CKEDITOR.editor} editor The editor instance.
* @example
*/
CKEDITOR.ui = function( editor )
{
if ( editor.ui )
return editor.ui;
/**
* Object used to hold private stuff.
* @private
*/
this._ =
{
handlers : {},
items : {},
editor : editor
};
return this;
};
// PACKAGER_RENAME( CKEDITOR.ui )
CKEDITOR.ui.prototype =
{
/**
* Adds a UI item to the items collection. These items can be later used in
* the interface.
* @param {String} name The UI item name.
* @param {Object} type The item type.
* @param {Object} definition The item definition. The properties of this
* object depend on the item type.
* @example
* // Add a new button named "MyBold".
* editorInstance.ui.add( 'MyBold', CKEDITOR.UI_BUTTON,
* {
* label : 'My Bold',
* command : 'bold'
* });
*/
add : function( name, type, definition )
{
this._.items[ name ] =
{
type : type,
// The name of {@link CKEDITOR.command} which associate with this UI.
command : definition.command || null,
args : Array.prototype.slice.call( arguments, 2 )
};
},
/**
* Gets a UI object.
* @param {String} name The UI item hame.
* @example
*/
create : function( name )
{
var item = this._.items[ name ],
handler = item && this._.handlers[ item.type ],
command = item && item.command && this._.editor.getCommand( item.command );
var result = handler && handler.create.apply( this, item.args );
// Allow overrides from skin ui definitions..
item && ( result = CKEDITOR.tools.extend( result, this._.editor.skin[ item.type ], true ) );
// Add reference inside command object.
if ( command )
command.uiItems.push( result );
return result;
},
/**
* Adds a handler for a UI item type. The handler is responsible for
* transforming UI item definitions in UI objects.
* @param {Object} type The item type.
* @param {Object} handler The handler definition.
* @example
*/
addHandler : function( type, handler )
{
this._.handlers[ type ] = handler;
}
};
CKEDITOR.event.implementOn( CKEDITOR.ui );
/**
* (Virtual Class) Do not call this constructor. This class is not really part
* of the API. It just illustrates the features of hanlder objects to be
* passed to the {@link CKEDITOR.ui.prototype.addHandler} function.
* @name CKEDITOR.ui.handlerDefinition
* @constructor
* @example
*/
/**
* Transforms an item definition into an UI item object.
* @name CKEDITOR.handlerDefinition.prototype.create
* @function
* @param {Object} definition The item definition.
* @example
* editorInstance.ui.addHandler( CKEDITOR.UI_BUTTON,
* {
* create : function( definition )
* {
* return new CKEDITOR.ui.button( definition );
* }
* });
*/
/**
* Internal event fired when a new UI element is ready
* @name CKEDITOR.ui#ready
* @event
* @param {Object} element The new element
*/
| JavaScript |
/*
Copyright (c) 2003-2011, CKSource - Frederico Knabben. All rights reserved.
For licensing, see LICENSE.html or http://ckeditor.com/license
*/
/**
* @fileOverview Defines the {@link CKEDITOR.themes} object, which is used to
* manage themes registration and loading.
*/
/**
* Manages themes registration and loading.
* @namespace
* @augments CKEDITOR.resourceManager
* @example
*/
CKEDITOR.themes = new CKEDITOR.resourceManager(
'_source/'+ // @Packager.RemoveLine
'themes/', 'theme' );
| JavaScript |
/*
Copyright (c) 2003-2011, CKSource - Frederico Knabben. All rights reserved.
For licensing, see LICENSE.html or http://ckeditor.com/license
*/
/**
* @fileOverview Defines the {@link CKEDITOR.skins} object, which is used to
* manage skins loading.
*/
/**
* Manages skins loading.
* @namespace
* @example
*/
CKEDITOR.skins = (function()
{
// Holds the list of loaded skins.
var loaded = {},
paths = {};
var loadPart = function( editor, skinName, part, callback )
{
// Get the skin definition.
var skinDefinition = loaded[ skinName ];
if ( !editor.skin )
{
editor.skin = skinDefinition;
// Trigger init function if any.
if ( skinDefinition.init )
skinDefinition.init( editor );
}
var appendSkinPath = function( fileNames )
{
for ( var n = 0 ; n < fileNames.length ; n++ )
{
fileNames[ n ] = CKEDITOR.getUrl( paths[ skinName ] + fileNames[ n ] );
}
};
function fixCSSTextRelativePath( cssStyleText, baseUrl )
{
return cssStyleText.replace( /url\s*\(([\s'"]*)(.*?)([\s"']*)\)/g,
function( match, opener, path, closer )
{
if ( /^\/|^\w?:/.test( path ) )
return match;
else
return 'url(' + baseUrl + opener + path + closer + ')';
} );
}
// Get the part definition.
part = skinDefinition[ part ];
var partIsLoaded = !part || !!part._isLoaded;
// Call the callback immediately if already loaded.
if ( partIsLoaded )
callback && callback();
else
{
// Put the callback in a queue.
var pending = part._pending || ( part._pending = [] );
pending.push( callback );
// We may have more than one skin part load request. Just the first
// one must do the loading job.
if ( pending.length > 1 )
return;
// Check whether the "css" and "js" properties have been defined
// for that part.
var cssIsLoaded = !part.css || !part.css.length,
jsIsLoaded = !part.js || !part.js.length;
// This is the function that will trigger the callback calls on
// load.
var checkIsLoaded = function()
{
if ( cssIsLoaded && jsIsLoaded )
{
// Mark the part as loaded.
part._isLoaded = 1;
// Call all pending callbacks.
for ( var i = 0 ; i < pending.length ; i++ )
{
if ( pending[ i ] )
pending[ i ]();
}
}
};
// Load the "css" pieces.
if ( !cssIsLoaded )
{
var cssPart = part.css;
if ( CKEDITOR.tools.isArray( cssPart ) )
{
appendSkinPath( cssPart );
for ( var c = 0 ; c < cssPart.length ; c++ )
CKEDITOR.document.appendStyleSheet( cssPart[ c ] );
}
else
{
cssPart = fixCSSTextRelativePath(
cssPart, CKEDITOR.getUrl( paths[ skinName ] ) );
// Processing Inline CSS part.
CKEDITOR.document.appendStyleText( cssPart );
}
part.css = cssPart;
cssIsLoaded = 1;
}
// Load the "js" pieces.
if ( !jsIsLoaded )
{
appendSkinPath( part.js );
CKEDITOR.scriptLoader.load( part.js, function()
{
jsIsLoaded = 1;
checkIsLoaded();
});
}
// We may have nothing to load, so check it immediately.
checkIsLoaded();
}
};
return /** @lends CKEDITOR.skins */ {
/**
* Registers a skin definition.
* @param {String} skinName The skin name.
* @param {Object} skinDefinition The skin definition.
* @example
*/
add : function( skinName, skinDefinition )
{
loaded[ skinName ] = skinDefinition;
skinDefinition.skinPath = paths[ skinName ]
|| ( paths[ skinName ] =
CKEDITOR.getUrl(
'_source/' + // @Packager.RemoveLine
'skins/' + skinName + '/' ) );
},
/**
* Loads a skin part. Skins are defined in parts, which are basically
* separated CSS files. This function is mainly used by the core code and
* should not have much use out of it.
* @param {String} skinName The name of the skin to be loaded.
* @param {String} skinPart The skin part to be loaded. Common skin parts
* are "editor" and "dialog".
* @param {Function} [callback] A function to be called once the skin
* part files are loaded.
* @example
*/
load : function( editor, skinPart, callback )
{
var skinName = editor.skinName,
skinPath = editor.skinPath;
if ( loaded[ skinName ] )
loadPart( editor, skinName, skinPart, callback );
else
{
paths[ skinName ] = skinPath;
CKEDITOR.scriptLoader.load( CKEDITOR.getUrl( skinPath + 'skin.js' ), function()
{
loadPart( editor, skinName, skinPart, callback );
});
}
}
};
})();
| JavaScript |
/*
Copyright (c) 2003-2011, CKSource - Frederico Knabben. All rights reserved.
For licensing, see LICENSE.html or http://ckeditor.com/license
*/
/**
* @fileOverview Defines the {@link CKEDITOR.plugins} object, which is used to
* manage plugins registration and loading.
*/
/**
* Manages plugins registration and loading.
* @namespace
* @augments CKEDITOR.resourceManager
* @example
*/
CKEDITOR.plugins = new CKEDITOR.resourceManager(
'_source/' + // @Packager.RemoveLine
'plugins/', 'plugin' );
// PACKAGER_RENAME( CKEDITOR.plugins )
CKEDITOR.plugins.load = CKEDITOR.tools.override( CKEDITOR.plugins.load, function( originalLoad )
{
return function( name, callback, scope )
{
var allPlugins = {};
var loadPlugins = function( names )
{
originalLoad.call( this, names, function( plugins )
{
CKEDITOR.tools.extend( allPlugins, plugins );
var requiredPlugins = [];
for ( var pluginName in plugins )
{
var plugin = plugins[ pluginName ],
requires = plugin && plugin.requires;
if ( requires )
{
for ( var i = 0 ; i < requires.length ; i++ )
{
if ( !allPlugins[ requires[ i ] ] )
requiredPlugins.push( requires[ i ] );
}
}
}
if ( requiredPlugins.length )
loadPlugins.call( this, requiredPlugins );
else
{
// Call the "onLoad" function for all plugins.
for ( pluginName in allPlugins )
{
plugin = allPlugins[ pluginName ];
if ( plugin.onLoad && !plugin.onLoad._called )
{
plugin.onLoad();
plugin.onLoad._called = 1;
}
}
// Call the callback.
if ( callback )
callback.call( scope || window, allPlugins );
}
}
, this);
};
loadPlugins.call( this, name );
};
});
/**
* Loads a specific language file, or auto detect it. A callback is
* then called when the file gets loaded.
* @param {String} pluginName The name of the plugin to which the provided translation
* should be attached.
* @param {String} languageCode The code of the language translation provided.
* @param {Object} languageEntries An object that contains pairs of label and
* the respective translation.
* @example
* CKEDITOR.plugins.setLang( 'myPlugin', 'en', {
* title : 'My plugin',
* selectOption : 'Please select an option'
* } );
*/
CKEDITOR.plugins.setLang = function( pluginName, languageCode, languageEntries )
{
var plugin = this.get( pluginName ),
pluginLangEntries = plugin.langEntries || ( plugin.langEntries = {} ),
pluginLang = plugin.lang || ( plugin.lang = [] );
if ( CKEDITOR.tools.indexOf( pluginLang, languageCode ) == -1 )
pluginLang.push( languageCode );
pluginLangEntries[ languageCode ] = languageEntries;
};
| JavaScript |
/*
Copyright (c) 2003-2011, CKSource - Frederico Knabben. All rights reserved.
For licensing, see LICENSE.html or http://ckeditor.com/license
*/
/**
* @fileOverview Defines the {@link CKEDITOR.tools} object, which contains
* utility functions.
*/
(function()
{
var functions = [];
CKEDITOR.on( 'reset', function()
{
functions = [];
});
/**
* Utility functions.
* @namespace
* @example
*/
CKEDITOR.tools =
{
/**
* Compare the elements of two arrays.
* @param {Array} arrayA An array to be compared.
* @param {Array} arrayB The other array to be compared.
* @returns {Boolean} "true" is the arrays have the same lenght and
* their elements match.
* @example
* var a = [ 1, 'a', 3 ];
* var b = [ 1, 3, 'a' ];
* var c = [ 1, 'a', 3 ];
* var d = [ 1, 'a', 3, 4 ];
*
* alert( CKEDITOR.tools.arrayCompare( a, b ) ); // false
* alert( CKEDITOR.tools.arrayCompare( a, c ) ); // true
* alert( CKEDITOR.tools.arrayCompare( a, d ) ); // false
*/
arrayCompare : function( arrayA, arrayB )
{
if ( !arrayA && !arrayB )
return true;
if ( !arrayA || !arrayB || arrayA.length != arrayB.length )
return false;
for ( var i = 0 ; i < arrayA.length ; i++ )
{
if ( arrayA[ i ] != arrayB[ i ] )
return false;
}
return true;
},
/**
* Creates a deep copy of an object.
* Attention: there is no support for recursive references.
* @param {Object} object The object to be cloned.
* @returns {Object} The object clone.
* @example
* var obj =
* {
* name : 'John',
* cars :
* {
* Mercedes : { color : 'blue' },
* Porsche : { color : 'red' }
* }
* };
* var clone = CKEDITOR.tools.clone( obj );
* clone.name = 'Paul';
* clone.cars.Porsche.color = 'silver';
* alert( obj.name ); // John
* alert( clone.name ); // Paul
* alert( obj.cars.Porsche.color ); // red
* alert( clone.cars.Porsche.color ); // silver
*/
clone : function( obj )
{
var clone;
// Array.
if ( obj && ( obj instanceof Array ) )
{
clone = [];
for ( var i = 0 ; i < obj.length ; i++ )
clone[ i ] = this.clone( obj[ i ] );
return clone;
}
// "Static" types.
if ( obj === null
|| ( typeof( obj ) != 'object' )
|| ( obj instanceof String )
|| ( obj instanceof Number )
|| ( obj instanceof Boolean )
|| ( obj instanceof Date )
|| ( obj instanceof RegExp) )
{
return obj;
}
// Objects.
clone = new obj.constructor();
for ( var propertyName in obj )
{
var property = obj[ propertyName ];
clone[ propertyName ] = this.clone( property );
}
return clone;
},
/**
* Turn the first letter of string to upper-case.
* @param {String} str
*/
capitalize: function( str )
{
return str.charAt( 0 ).toUpperCase() + str.substring( 1 ).toLowerCase();
},
/**
* Copy the properties from one object to another. By default, properties
* already present in the target object <strong>are not</strong> overwritten.
* @param {Object} target The object to be extended.
* @param {Object} source[,souce(n)] The objects from which copy
* properties. Any number of objects can be passed to this function.
* @param {Boolean} [overwrite] If 'true' is specified it indicates that
* properties already present in the target object could be
* overwritten by subsequent objects.
* @param {Object} [properties] Only properties within the specified names
* list will be received from the source object.
* @returns {Object} the extended object (target).
* @example
* // Create the sample object.
* var myObject =
* {
* prop1 : true
* };
*
* // Extend the above object with two properties.
* CKEDITOR.tools.extend( myObject,
* {
* prop2 : true,
* prop3 : true
* } );
*
* // Alert "prop1", "prop2" and "prop3".
* for ( var p in myObject )
* alert( p );
*/
extend : function( target )
{
var argsLength = arguments.length,
overwrite, propertiesList;
if ( typeof ( overwrite = arguments[ argsLength - 1 ] ) == 'boolean')
argsLength--;
else if ( typeof ( overwrite = arguments[ argsLength - 2 ] ) == 'boolean' )
{
propertiesList = arguments [ argsLength -1 ];
argsLength-=2;
}
for ( var i = 1 ; i < argsLength ; i++ )
{
var source = arguments[ i ];
for ( var propertyName in source )
{
// Only copy existed fields if in overwrite mode.
if ( overwrite === true || target[ propertyName ] == undefined )
{
// Only copy specified fields if list is provided.
if ( !propertiesList || ( propertyName in propertiesList ) )
target[ propertyName ] = source[ propertyName ];
}
}
}
return target;
},
/**
* Creates an object which is an instance of a class which prototype is a
* predefined object. All properties defined in the source object are
* automatically inherited by the resulting object, including future
* changes to it.
* @param {Object} source The source object to be used as the prototype for
* the final object.
* @returns {Object} The resulting copy.
*/
prototypedCopy : function( source )
{
var copy = function()
{};
copy.prototype = source;
return new copy();
},
/**
* Checks if an object is an Array.
* @param {Object} object The object to be checked.
* @type Boolean
* @returns <i>true</i> if the object is an Array, otherwise <i>false</i>.
* @example
* alert( CKEDITOR.tools.isArray( [] ) ); // "true"
* alert( CKEDITOR.tools.isArray( 'Test' ) ); // "false"
*/
isArray : function( object )
{
return ( !!object && object instanceof Array );
},
/**
* Whether the object contains no properties of it's own.
* @param object
*/
isEmpty : function ( object )
{
for ( var i in object )
{
if ( object.hasOwnProperty( i ) )
return false;
}
return true;
},
/**
* Transforms a CSS property name to its relative DOM style name.
* @param {String} cssName The CSS property name.
* @returns {String} The transformed name.
* @example
* alert( CKEDITOR.tools.cssStyleToDomStyle( 'background-color' ) ); // "backgroundColor"
* alert( CKEDITOR.tools.cssStyleToDomStyle( 'float' ) ); // "cssFloat"
*/
cssStyleToDomStyle : ( function()
{
var test = document.createElement( 'div' ).style;
var cssFloat = ( typeof test.cssFloat != 'undefined' ) ? 'cssFloat'
: ( typeof test.styleFloat != 'undefined' ) ? 'styleFloat'
: 'float';
return function( cssName )
{
if ( cssName == 'float' )
return cssFloat;
else
{
return cssName.replace( /-./g, function( match )
{
return match.substr( 1 ).toUpperCase();
});
}
};
} )(),
/**
* Build the HTML snippet of a set of <style>/<link>.
* @param css {String|Array} Each of which are url (absolute) of a CSS file or
* a trunk of style text.
*/
buildStyleHtml : function ( css )
{
css = [].concat( css );
var item, retval = [];
for ( var i = 0; i < css.length; i++ )
{
item = css[ i ];
// Is CSS style text ?
if ( /@import|[{}]/.test(item) )
retval.push('<style>' + item + '</style>');
else
retval.push('<link type="text/css" rel=stylesheet href="' + item + '">');
}
return retval.join( '' );
},
/**
* Replace special HTML characters in a string with their relative HTML
* entity values.
* @param {String} text The string to be encoded.
* @returns {String} The encode string.
* @example
* alert( CKEDITOR.tools.htmlEncode( 'A > B & C < D' ) ); // "A &gt; B &amp; C &lt; D"
*/
htmlEncode : function( text )
{
var standard = function( text )
{
var span = new CKEDITOR.dom.element( 'span' );
span.setText( text );
return span.getHtml();
};
var fix1 = ( standard( '\n' ).toLowerCase() == '<br>' ) ?
function( text )
{
// #3874 IE and Safari encode line-break into <br>
return standard( text ).replace( /<br>/gi, '\n' );
} :
standard;
var fix2 = ( standard( '>' ) == '>' ) ?
function( text )
{
// WebKit does't encode the ">" character, which makes sense, but
// it's different than other browsers.
return fix1( text ).replace( />/g, '>' );
} :
fix1;
var fix3 = ( standard( ' ' ) == ' ' ) ?
function( text )
{
// #3785 IE8 changes spaces (>= 2) to
return fix2( text ).replace( / /g, ' ' );
} :
fix2;
this.htmlEncode = fix3;
return this.htmlEncode( text );
},
/**
* Replace special HTML characters in HTMLElement's attribute with their relative HTML entity values.
* @param {String} The attribute's value to be encoded.
* @returns {String} The encode value.
* @example
* element.setAttribute( 'title', '<a " b >' );
* alert( CKEDITOR.tools.htmlEncodeAttr( element.getAttribute( 'title' ) ); // ">a " b <"
*/
htmlEncodeAttr : function( text )
{
return text.replace( /"/g, '"' ).replace( /</g, '<' ).replace( />/g, '>' );
},
/**
* Gets a unique number for this CKEDITOR execution session. It returns
* progressive numbers starting at 1.
* @function
* @returns {Number} A unique number.
* @example
* alert( CKEDITOR.tools.<b>getNextNumber()</b> ); // "1" (e.g.)
* alert( CKEDITOR.tools.<b>getNextNumber()</b> ); // "2"
*/
getNextNumber : (function()
{
var last = 0;
return function()
{
return ++last;
};
})(),
/**
* Gets a unique ID for CKEditor's interface elements. It returns a
* string with the "cke_" prefix and a progressive number.
* @function
* @returns {String} A unique ID.
* @example
* alert( CKEDITOR.tools.<b>getNextId()</b> ); // "cke_1" (e.g.)
* alert( CKEDITOR.tools.<b>getNextId()</b> ); // "cke_2"
*/
getNextId : function()
{
return 'cke_' + this.getNextNumber();
},
/**
* Creates a function override.
* @param {Function} originalFunction The function to be overridden.
* @param {Function} functionBuilder A function that returns the new
* function. The original function reference will be passed to this
* function.
* @returns {Function} The new function.
* @example
* var example =
* {
* myFunction : function( name )
* {
* alert( 'Name: ' + name );
* }
* };
*
* example.myFunction = CKEDITOR.tools.override( example.myFunction, function( myFunctionOriginal )
* {
* return function( name )
* {
* alert( 'Override Name: ' + name );
* myFunctionOriginal.call( this, name );
* };
* });
*/
override : function( originalFunction, functionBuilder )
{
return functionBuilder( originalFunction );
},
/**
* Executes a function after specified delay.
* @param {Function} func The function to be executed.
* @param {Number} [milliseconds] The amount of time (millisecods) to wait
* to fire the function execution. Defaults to zero.
* @param {Object} [scope] The object to hold the function execution scope
* (the "this" object). By default the "window" object.
* @param {Object|Array} [args] A single object, or an array of objects, to
* pass as arguments to the function.
* @param {Object} [ownerWindow] The window that will be used to set the
* timeout. By default the current "window".
* @returns {Object} A value that can be used to cancel the function execution.
* @example
* CKEDITOR.tools.<b>setTimeout(
* function()
* {
* alert( 'Executed after 2 seconds' );
* },
* 2000 )</b>;
*/
setTimeout : function( func, milliseconds, scope, args, ownerWindow )
{
if ( !ownerWindow )
ownerWindow = window;
if ( !scope )
scope = ownerWindow;
return ownerWindow.setTimeout(
function()
{
if ( args )
func.apply( scope, [].concat( args ) ) ;
else
func.apply( scope ) ;
},
milliseconds || 0 );
},
/**
* Remove spaces from the start and the end of a string. The following
* characters are removed: space, tab, line break, line feed.
* @function
* @param {String} str The text from which remove the spaces.
* @returns {String} The modified string without the boundary spaces.
* @example
* alert( CKEDITOR.tools.trim( ' example ' ); // "example"
*/
trim : (function()
{
// We are not using \s because we don't want "non-breaking spaces" to be caught.
var trimRegex = /(?:^[ \t\n\r]+)|(?:[ \t\n\r]+$)/g;
return function( str )
{
return str.replace( trimRegex, '' ) ;
};
})(),
/**
* Remove spaces from the start (left) of a string. The following
* characters are removed: space, tab, line break, line feed.
* @function
* @param {String} str The text from which remove the spaces.
* @returns {String} The modified string excluding the removed spaces.
* @example
* alert( CKEDITOR.tools.ltrim( ' example ' ); // "example "
*/
ltrim : (function()
{
// We are not using \s because we don't want "non-breaking spaces" to be caught.
var trimRegex = /^[ \t\n\r]+/g;
return function( str )
{
return str.replace( trimRegex, '' ) ;
};
})(),
/**
* Remove spaces from the end (right) of a string. The following
* characters are removed: space, tab, line break, line feed.
* @function
* @param {String} str The text from which remove the spaces.
* @returns {String} The modified string excluding the removed spaces.
* @example
* alert( CKEDITOR.tools.ltrim( ' example ' ); // " example"
*/
rtrim : (function()
{
// We are not using \s because we don't want "non-breaking spaces" to be caught.
var trimRegex = /[ \t\n\r]+$/g;
return function( str )
{
return str.replace( trimRegex, '' ) ;
};
})(),
/**
* Returns the index of an element in an array.
* @param {Array} array The array to be searched.
* @param {Object} entry The element to be found.
* @returns {Number} The (zero based) index of the first entry that matches
* the entry, or -1 if not found.
* @example
* var letters = [ 'a', 'b', 0, 'c', false ];
* alert( CKEDITOR.tools.indexOf( letters, '0' ) ); "-1" because 0 !== '0'
* alert( CKEDITOR.tools.indexOf( letters, false ) ); "4" because 0 !== false
*/
indexOf :
// #2514: We should try to use Array.indexOf if it does exist.
( Array.prototype.indexOf ) ?
function( array, entry )
{
return array.indexOf( entry );
}
:
function( array, entry )
{
for ( var i = 0, len = array.length ; i < len ; i++ )
{
if ( array[ i ] === entry )
return i;
}
return -1;
},
/**
* Creates a function that will always execute in the context of a
* specified object.
* @param {Function} func The function to be executed.
* @param {Object} obj The object to which bind the execution context.
* @returns {Function} The function that can be used to execute the
* "func" function in the context of "obj".
* @example
* var obj = { text : 'My Object' };
*
* function alertText()
* {
* alert( this.text );
* }
*
* var newFunc = <b>CKEDITOR.tools.bind( alertText, obj )</b>;
* newFunc(); // Alerts "My Object".
*/
bind : function( func, obj )
{
return function() { return func.apply( obj, arguments ); };
},
/**
* Class creation based on prototype inheritance, with supports of the
* following features:
* <ul>
* <li> Static fields </li>
* <li> Private fields </li>
* <li> Public (prototype) fields </li>
* <li> Chainable base class constructor </li>
* </ul>
* @param {Object} definition The class definition object.
* @returns {Function} A class-like JavaScript function.
*/
createClass : function( definition )
{
var $ = definition.$,
baseClass = definition.base,
privates = definition.privates || definition._,
proto = definition.proto,
statics = definition.statics;
if ( privates )
{
var originalConstructor = $;
$ = function()
{
// Create (and get) the private namespace.
var _ = this._ || ( this._ = {} );
// Make some magic so "this" will refer to the main
// instance when coding private functions.
for ( var privateName in privates )
{
var priv = privates[ privateName ];
_[ privateName ] =
( typeof priv == 'function' ) ? CKEDITOR.tools.bind( priv, this ) : priv;
}
originalConstructor.apply( this, arguments );
};
}
if ( baseClass )
{
$.prototype = this.prototypedCopy( baseClass.prototype );
$.prototype.constructor = $;
$.prototype.base = function()
{
this.base = baseClass.prototype.base;
baseClass.apply( this, arguments );
this.base = arguments.callee;
};
}
if ( proto )
this.extend( $.prototype, proto, true );
if ( statics )
this.extend( $, statics, true );
return $;
},
/**
* Creates a function reference that can be called later using
* CKEDITOR.tools.callFunction. This approach is specially useful to
* make DOM attribute function calls to JavaScript defined functions.
* @param {Function} fn The function to be executed on call.
* @param {Object} [scope] The object to have the context on "fn" execution.
* @returns {Number} A unique reference to be used in conjuction with
* CKEDITOR.tools.callFunction.
* @example
* var ref = <b>CKEDITOR.tools.addFunction</b>(
* function()
* {
* alert( 'Hello!');
* });
* CKEDITOR.tools.callFunction( ref ); // Hello!
*/
addFunction : function( fn, scope )
{
return functions.push( function()
{
return fn.apply( scope || this, arguments );
}) - 1;
},
/**
* Removes the function reference created with {@see CKEDITOR.tools.addFunction}.
* @param {Number} ref The function reference created with
* CKEDITOR.tools.addFunction.
*/
removeFunction : function( ref )
{
functions[ ref ] = null;
},
/**
* Executes a function based on the reference created with
* CKEDITOR.tools.addFunction.
* @param {Number} ref The function reference created with
* CKEDITOR.tools.addFunction.
* @param {[Any,[Any,...]} params Any number of parameters to be passed
* to the executed function.
* @returns {Any} The return value of the function.
* @example
* var ref = CKEDITOR.tools.addFunction(
* function()
* {
* alert( 'Hello!');
* });
* <b>CKEDITOR.tools.callFunction( ref )</b>; // Hello!
*/
callFunction : function( ref )
{
var fn = functions[ ref ];
return fn && fn.apply( window, Array.prototype.slice.call( arguments, 1 ) );
},
/**
* Append the 'px' length unit to the size if it's missing.
* @param length
*/
cssLength : (function()
{
return function( length )
{
return length + ( !length || isNaN( Number( length ) ) ? '' : 'px' );
};
})(),
/**
* Convert the specified CSS length value to the calculated pixel length inside this page.
* <strong>Note:</strong> Percentage based value is left intact.
* @param {String} cssLength CSS length value.
*/
convertToPx : ( function ()
{
var calculator;
return function( cssLength )
{
if ( !calculator )
{
calculator = CKEDITOR.dom.element.createFromHtml(
'<div style="position:absolute;left:-9999px;' +
'top:-9999px;margin:0px;padding:0px;border:0px;"' +
'></div>', CKEDITOR.document );
CKEDITOR.document.getBody().append( calculator );
}
if ( !(/%$/).test( cssLength ) )
{
calculator.setStyle( 'width', cssLength );
return calculator.$.clientWidth;
}
return cssLength;
};
} )(),
/**
* String specified by {@param str} repeats {@param times} times.
* @param str
* @param times
*/
repeat : function( str, times )
{
return new Array( times + 1 ).join( str );
},
/**
* Return the first successfully executed function's return value that
* doesn't throw any exception.
*/
tryThese : function()
{
var returnValue;
for ( var i = 0, length = arguments.length; i < length; i++ )
{
var lambda = arguments[i];
try
{
returnValue = lambda();
break;
}
catch (e) {}
}
return returnValue;
},
/**
* Generate a combined key from a series of params.
* @param {String} subKey One or more string used as sub keys.
* @example
* var key = CKEDITOR.tools.genKey( 'key1', 'key2', 'key3' );
* alert( key ); // "key1-key2-key3".
*/
genKey : function()
{
return Array.prototype.slice.call( arguments ).join( '-' );
}
};
})();
// PACKAGER_RENAME( CKEDITOR.tools )
| JavaScript |
/*
Copyright (c) 2003-2011, CKSource - Frederico Knabben. All rights reserved.
For licensing, see LICENSE.html or http://ckeditor.com/license
*/
/**
* @fileOverview Defines the {@link CKEDITOR.loader} objects, which is used to
* load core scripts and their dependencies from _source.
*/
if ( typeof CKEDITOR == 'undefined' )
CKEDITOR = {};
if ( !CKEDITOR.loader )
{
/**
* Load core scripts and their dependencies from _source.
* @namespace
* @example
*/
CKEDITOR.loader = (function()
{
// Table of script names and their dependencies.
var scripts =
{
'core/_bootstrap' : [ 'core/config', 'core/ckeditor', 'core/plugins', 'core/scriptloader', 'core/tools', /* The following are entries that we want to force loading at the end to avoid dependence recursion */ 'core/dom/comment', 'core/dom/elementpath', 'core/dom/text', 'core/dom/rangelist' ],
'core/ckeditor' : [ 'core/ckeditor_basic', 'core/dom', 'core/dtd', 'core/dom/document', 'core/dom/element', 'core/editor', 'core/event', 'core/htmlparser', 'core/htmlparser/element', 'core/htmlparser/fragment', 'core/htmlparser/filter', 'core/htmlparser/basicwriter', 'core/tools' ],
'core/ckeditor_base' : [],
'core/ckeditor_basic' : [ 'core/editor_basic', 'core/env', 'core/event' ],
'core/command' : [],
'core/config' : [ 'core/ckeditor_base' ],
'core/dom' : [],
'core/dom/comment' : [ 'core/dom/node' ],
'core/dom/document' : [ 'core/dom', 'core/dom/domobject', 'core/dom/window' ],
'core/dom/documentfragment' : [ 'core/dom/element' ],
'core/dom/element' : [ 'core/dom', 'core/dom/document', 'core/dom/domobject', 'core/dom/node', 'core/dom/nodelist', 'core/tools' ],
'core/dom/elementpath' : [ 'core/dom/element' ],
'core/dom/event' : [],
'core/dom/node' : [ 'core/dom/domobject', 'core/tools' ],
'core/dom/nodelist' : [ 'core/dom/node' ],
'core/dom/domobject' : [ 'core/dom/event' ],
'core/dom/range' : [ 'core/dom/document', 'core/dom/documentfragment', 'core/dom/element', 'core/dom/walker' ],
'core/dom/rangelist' : [ 'core/dom/range' ],
'core/dom/text' : [ 'core/dom/node', 'core/dom/domobject' ],
'core/dom/walker' : [ 'core/dom/node' ],
'core/dom/window' : [ 'core/dom/domobject' ],
'core/dtd' : [ 'core/tools' ],
'core/editor' : [ 'core/command', 'core/config', 'core/editor_basic', 'core/focusmanager', 'core/lang', 'core/plugins', 'core/skins', 'core/themes', 'core/tools', 'core/ui' ],
'core/editor_basic' : [ 'core/event' ],
'core/env' : [],
'core/event' : [],
'core/focusmanager' : [],
'core/htmlparser' : [],
'core/htmlparser/comment' : [ 'core/htmlparser' ],
'core/htmlparser/element' : [ 'core/htmlparser', 'core/htmlparser/fragment' ],
'core/htmlparser/fragment' : [ 'core/htmlparser', 'core/htmlparser/comment', 'core/htmlparser/text', 'core/htmlparser/cdata' ],
'core/htmlparser/text' : [ 'core/htmlparser' ],
'core/htmlparser/cdata' : [ 'core/htmlparser' ],
'core/htmlparser/filter' : [ 'core/htmlparser' ],
'core/htmlparser/basicwriter': [ 'core/htmlparser' ],
'core/lang' : [],
'core/plugins' : [ 'core/resourcemanager' ],
'core/resourcemanager' : [ 'core/scriptloader', 'core/tools' ],
'core/scriptloader' : [ 'core/dom/element', 'core/env' ],
'core/skins' : [ 'core/scriptloader' ],
'core/themes' : [ 'core/resourcemanager' ],
'core/tools' : [ 'core/env' ],
'core/ui' : []
};
var basePath = (function()
{
// This is a copy of CKEDITOR.basePath, but requires the script having
// "_source/core/loader.js".
if ( CKEDITOR && CKEDITOR.basePath )
return CKEDITOR.basePath;
// Find out the editor directory path, based on its <script> tag.
var path = '';
var scripts = document.getElementsByTagName( 'script' );
for ( var i = 0 ; i < scripts.length ; i++ )
{
var match = scripts[i].src.match( /(^|.*?[\\\/])(?:_source\/)?core\/loader.js(?:\?.*)?$/i );
if ( match )
{
path = match[1];
break;
}
}
// In IE (only) the script.src string is the raw valued entered in the
// HTML. Other browsers return the full resolved URL instead.
if ( path.indexOf('://') == -1 )
{
// Absolute path.
if ( path.indexOf( '/' ) === 0 )
path = location.href.match( /^.*?:\/\/[^\/]*/ )[0] + path;
// Relative path.
else
path = location.href.match( /^[^\?]*\// )[0] + path;
}
return path;
})();
var timestamp = 'B8DJ5M3';
var getUrl = function( resource )
{
if ( CKEDITOR && CKEDITOR.getUrl )
return CKEDITOR.getUrl( resource );
return basePath + resource +
( resource.indexOf( '?' ) >= 0 ? '&' : '?' ) +
't=' + timestamp;
};
var pendingLoad = [];
/** @lends CKEDITOR.loader */
return {
/**
* The list of loaded scripts in their loading order.
* @type Array
* @example
* // Alert the loaded script names.
* alert( <b>CKEDITOR.loader.loadedScripts</b> );
*/
loadedScripts : [],
loadPending : function()
{
var scriptName = pendingLoad.shift();
if ( !scriptName )
return;
var scriptSrc = getUrl( '_source/' + scriptName + '.js' );
var script = document.createElement( 'script' );
script.type = 'text/javascript';
script.src = scriptSrc;
function onScriptLoaded()
{
// Append this script to the list of loaded scripts.
CKEDITOR.loader.loadedScripts.push( scriptName );
// Load the next.
CKEDITOR.loader.loadPending();
}
// We must guarantee the execution order of the scripts, so we
// need to load them one by one. (#4145)
// The following if/else block has been taken from the scriptloader core code.
if ( typeof(script.onreadystatechange) !== "undefined" )
{
/** @ignore */
script.onreadystatechange = function()
{
if ( script.readyState == 'loaded' || script.readyState == 'complete' )
{
script.onreadystatechange = null;
onScriptLoaded();
}
};
}
else
{
/** @ignore */
script.onload = function()
{
// Some browsers, such as Safari, may call the onLoad function
// immediately. Which will break the loading sequence. (#3661)
setTimeout( function() { onScriptLoaded( scriptName ); }, 0 );
};
}
document.body.appendChild( script );
},
/**
* Loads a specific script, including its dependencies. This is not a
* synchronous loading, which means that the code to be loaded will
* not necessarily be available after this call.
* @example
* CKEDITOR.loader.load( 'core/dom/element' );
*/
load : function( scriptName, defer )
{
// Check if the script has already been loaded.
if ( scriptName in this.loadedScripts )
return;
// Get the script dependencies list.
var dependencies = scripts[ scriptName ];
if ( !dependencies )
throw 'The script name"' + scriptName + '" is not defined.';
// Mark the script as loaded, even before really loading it, to
// avoid cross references recursion.
this.loadedScripts[ scriptName ] = true;
// Load all dependencies first.
for ( var i = 0 ; i < dependencies.length ; i++ )
this.load( dependencies[ i ], true );
var scriptSrc = getUrl( '_source/' + scriptName + '.js' );
// Append the <script> element to the DOM.
// If the page is fully loaded, we can't use document.write
// but if the script is run while the body is loading then it's safe to use it
// Unfortunately, Firefox <3.6 doesn't support document.readyState, so it won't get this improvement
if ( document.body && (!document.readyState || document.readyState == 'complete') )
{
pendingLoad.push( scriptName );
if ( !defer )
this.loadPending();
}
else
{
// Append this script to the list of loaded scripts.
this.loadedScripts.push( scriptName );
document.write( '<script src="' + scriptSrc + '" type="text/javascript"><\/script>' );
}
}
};
})();
}
// Check if any script has been defined for autoload.
if ( CKEDITOR._autoLoad )
{
CKEDITOR.loader.load( CKEDITOR._autoLoad );
delete CKEDITOR._autoLoad;
}
| JavaScript |
/*
Copyright (c) 2003-2011, CKSource - Frederico Knabben. All rights reserved.
For licensing, see LICENSE.html or http://ckeditor.com/license
*/
/**
* Creates a command class instance.
* @class Represents a command that can be executed on an editor instance.
* @param {CKEDITOR.editor} editor The editor instance this command will be
* related to.
* @param {CKEDITOR.commandDefinition} commandDefinition The command
* definition.
* @augments CKEDITOR.event
* @example
* var command = new CKEDITOR.command( editor,
* {
* exec : function( editor )
* {
* alert( editor.document.getBody().getHtml() );
* }
* });
*/
CKEDITOR.command = function( editor, commandDefinition )
{
/**
* Lists UI items that are associated to this command. This list can be
* used to interact with the UI on command execution (by the execution code
* itself, for example).
* @type Array
* @example
* alert( 'Number of UI items associated to this command: ' + command.<b>uiItems</b>.length );
*/
this.uiItems = [];
/**
* Executes the command.
* @param {Object} [data] Any data to pass to the command. Depends on the
* command implementation and requirements.
* @returns {Boolean} A boolean indicating that the command has been
* successfully executed.
* @example
* command.<b>exec()</b>; // The command gets executed.
*/
this.exec = function( data )
{
if ( this.state == CKEDITOR.TRISTATE_DISABLED )
return false;
if ( this.editorFocus ) // Give editor focus if necessary (#4355).
editor.focus();
return ( commandDefinition.exec.call( this, editor, data ) !== false );
};
CKEDITOR.tools.extend( this, commandDefinition,
// Defaults
/** @lends CKEDITOR.command.prototype */
{
/**
* The editor modes within which the command can be executed. The
* execution will have no action if the current mode is not listed
* in this property.
* @type Object
* @default { wysiwyg : 1 }
* @see CKEDITOR.editor.prototype.mode
* @example
* // Enable the command in both WYSIWYG and Source modes.
* command.<b>modes</b> = { wysiwyg : 1, source : 1 };
* @example
* // Enable the command in Source mode only.
* command.<b>modes</b> = { source : 1 };
*/
modes : { wysiwyg : 1 },
/**
* Indicates that the editor will get the focus before executing
* the command.
* @type Boolean
* @default true
* @example
* // Do not force the editor to have focus when executing the command.
* command.<b>editorFocus</b> = false;
*/
editorFocus : 1,
/**
* Indicates the editor state. Possible values are:
* <ul>
* <li>{@link CKEDITOR.TRISTATE_DISABLED}: the command is
* disabled. It's execution will have no effect. Same as
* {@link disable}.</li>
* <li>{@link CKEDITOR.TRISTATE_ON}: the command is enabled
* and currently active in the editor (for context sensitive commands,
* for example).</li>
* <li>{@link CKEDITOR.TRISTATE_OFF}: the command is enabled
* and currently inactive in the editor (for context sensitive
* commands, for example).</li>
* </ul>
* Do not set this property directly, using the {@link #setState}
* method instead.
* @type Number
* @default {@link CKEDITOR.TRISTATE_OFF}
* @example
* if ( command.<b>state</b> == CKEDITOR.TRISTATE_DISABLED )
* alert( 'This command is disabled' );
*/
state : CKEDITOR.TRISTATE_OFF
});
// Call the CKEDITOR.event constructor to initialize this instance.
CKEDITOR.event.call( this );
};
CKEDITOR.command.prototype =
{
/**
* Enables the command for execution. The command state (see
* {@link CKEDITOR.command.prototype.state}) available before disabling it
* is restored.
* @example
* command.<b>enable()</b>;
* command.exec(); // Execute the command.
*/
enable : function()
{
if ( this.state == CKEDITOR.TRISTATE_DISABLED )
this.setState( ( !this.preserveState || ( typeof this.previousState == 'undefined' ) ) ? CKEDITOR.TRISTATE_OFF : this.previousState );
},
/**
* Disables the command for execution. The command state (see
* {@link CKEDITOR.command.prototype.state}) will be set to
* {@link CKEDITOR.TRISTATE_DISABLED}.
* @example
* command.<b>disable()</b>;
* command.exec(); // "false" - Nothing happens.
*/
disable : function()
{
this.setState( CKEDITOR.TRISTATE_DISABLED );
},
/**
* Sets the command state.
* @param {Number} newState The new state. See {@link #state}.
* @returns {Boolean} Returns "true" if the command state changed.
* @example
* command.<b>setState( CKEDITOR.TRISTATE_ON )</b>;
* command.exec(); // Execute the command.
* command.<b>setState( CKEDITOR.TRISTATE_DISABLED )</b>;
* command.exec(); // "false" - Nothing happens.
* command.<b>setState( CKEDITOR.TRISTATE_OFF )</b>;
* command.exec(); // Execute the command.
*/
setState : function( newState )
{
// Do nothing if there is no state change.
if ( this.state == newState )
return false;
this.previousState = this.state;
// Set the new state.
this.state = newState;
// Fire the "state" event, so other parts of the code can react to the
// change.
this.fire( 'state' );
return true;
},
/**
* Toggles the on/off (active/inactive) state of the command. This is
* mainly used internally by context sensitive commands.
* @example
* command.<b>toggleState()</b>;
*/
toggleState : function()
{
if ( this.state == CKEDITOR.TRISTATE_OFF )
this.setState( CKEDITOR.TRISTATE_ON );
else if ( this.state == CKEDITOR.TRISTATE_ON )
this.setState( CKEDITOR.TRISTATE_OFF );
}
};
CKEDITOR.event.implementOn( CKEDITOR.command.prototype, true );
/**
* Indicates the previous command state.
* @name CKEDITOR.command.prototype.previousState
* @type Number
* @see #state
* @example
* alert( command.<b>previousState</b> );
*/
/**
* Fired when the command state changes.
* @name CKEDITOR.command#state
* @event
* @example
* command.on( <b>'state'</b> , function( e )
* {
* // Alerts the new state.
* alert( this.state );
* });
*/
| JavaScript |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.