Language: JavaScript
Untitled JavaScript (7-Aug @ 16:02)
Syntax Highlighted Code
- $("input.all").click(function(){
- var t = $(this);
- var c = $(':checked', t).length;
- [5 more lines...]
Plain Code
$("input.all").click(function(){
var t = $(this);
var c = $(':checked', t).length;
if (c == 1) {
console.log("checked");
}
});
Untitled JavaScript (6-Aug @ 18:45)
Syntax Highlighted Code
- $(document).ready(function(){
- $('#video_box').hide();
- $('a.video-link', this).click(function(){
- $(this).next('#video_box').slideToggle();
- [8 more lines...]
Plain Code
$(document).ready(function(){
$('#video_box').hide();
$('a.video-link', this).click(function(){
$(this).next('#video_box').slideToggle();
return false;
});
$('a.video-close', this).click(function(){
$(this).parent('#video_box').hide();
return false;
}, function(){
$(this).siblings('#video_frame').empty();
})
});
Untitled JavaScript (6-Aug @ 14:33)
Syntax Highlighted Code
- /*
- Author : Vipul Limbachiya
- FileName : jQuery.presentation
- Reqires : jQuery.js,jQuery.init.js,jQuery-ui-personalized-1.5.2.js
- [802 more lines...]
Plain Code
/*
Author : Vipul Limbachiya
FileName : jQuery.presentation
Reqires : jQuery.js,jQuery.init.js,jQuery-ui-personalized-1.5.2.js
*/
function Elem(elemId){return document.getElementById(elemId);}
jQuery.preloadImages = function()
{
for(var i = 0; i<arguments.length; i++)
{
jQuery("<img>").attr("src", arguments[i]);
}
}
// Properties for handler classes and ID so later on we can change if required
var Properties = {
currentDayBoxClass: ".calDayCur",
calendarBoxId: "#clndrEvent",
eventContainerBoxId: "#events",
eventBoxClass: ".calEvent",
eventBoxClassOnDrag: ".calEventDrag"
};
// This class manages all AJAX requests and response, its integrated with Presentation class
var EventCallBack=
{
// This method is being called on drop of event box on day,
// Calls async page and retrives details of selected template and date.
// And generates form of event using presentation class
retriveEventTemplateDetais : function(eventBoxId,templateId,selDate)
{
Presentation.appendMessage(eventBoxId,
"Wait...");
$.ajax({type:"POST",
url: "asyncHandler/handlerEvents.ashx",
data: "act=getEventTemplateDetails&tempId=" + templateId + "&selDate=" + selDate,
success:function(serverResponseData)
{
EventCallBack.retriveEventTemplateDetaisSuccess(serverResponseData,selDate,eventBoxId);
},
error: function(reqObject,typeofError,exceptionObj)
{
EventCallBack.retriveEventTemplateDetaisFailure(eventBoxId);
},
complete: function()
{
Presentation.removeMessage(eventBoxId);
}
});
},
// Being called on success of method : retriveEventTemplateDetais
retriveEventTemplateDetaisSuccess:function(responseText,selDate,eventBoxId)
{
Presentation.refreshEventPanel();
data = eval("(" + responseText + ")");
if(parseInt(data.response.error)===0)
{
Presentation.generateMyReminderPanel(data.response.table,
selDate,
eventBoxId);
}
else
{
Presentation.alertMessage(data.response.message);
Presentation.resetEventBoxIdPosition(eventBoxId,"");
}
},
// Being called on failure of method : retriveEventTemplateDetais
retriveEventTemplateDetaisFailure:function(eventBoxId)
{
Presentation.alertMessage("Error occored while processing request on server!");
Presentation.resetEventBoxIdPosition(eventBoxId,"");
},
// Submits selected option and data of event form
submitEventData : function(eventBoxId)
{
if($("#myReminderPanel_isActive").val()=="yes")
{
Presentation.appendMessage("myReminderFormPanel",
"Please Wait...");
var frequencyOption = "";
$("#myReminderPanel_EventFreq_Panel > select option:selected").each(function () {
if(frequencyOption.length>0)
{
frequencyOption += $(this).text() + ",";
}
else
{
frequencyOption = $(this).text();
}
});
var reminderOption = "";
$("#myReminderPanel_EventReminder_Panel > select option:selected").each(function () {
if(reminderOption.length>0)
{
reminderOption += $(this).text() + ",";
}
else
{
reminderOption = $(this).text();
}
});
var SelectedDate = $("#myReminderPanel_EventDate").val();
var disableEmailReminder = false;
if(Elem("myReminderPanel_EventDisableEmailReminder"))
{
disableEmailReminder = Elem("myReminderPanel_EventDisableEmailReminder").checked;
}
var disableSMSReminder = false;
if(Elem("myReminderPanel_EventDisableSMSReminder"))
{
disableSMSReminder = Elem("myReminderPanel_EventDisableSMSReminder").checked;
}
$.ajax({type:"POST",
url: "asyncHandler/handlerEvents.ashx",
data: "act=add"
+ "&tempId=" + $("#myReminderPanel_EventTemplateId").val()
+ "&eventTitle=" + $("#myReminderPanel_EventTitle").val()
+ "&eventDate=" + SelectedDate
+ "&eventFreq=" + frequencyOption
+ "&eventReminder=" + reminderOption
+ "&disableEmailReminder=" + disableEmailReminder
+ "&disableSMSReminder=" + disableSMSReminder
+ "&eventAltEmail=" + $("#myReminderPanel_EventAltEmail").val()
+ "&eventAltMobile=" + $("#myReminderPanel_EventAltMobile").val(),
success:function(serverResponseData)
{
EventCallBack.submitEventDataSuccess(serverResponseData,SelectedDate);
},
error: function(reqObject,typeofError,exceptionObj)
{
EventCallBack.submitEventDataFailure(SelectedDate);
},
complete: function()
{
Presentation.removeMessage("myReminderFormPanel");
}
});
}
},
// Being called on success of method : submitEventData
submitEventDataSuccess:function(responseText,selDate)
{
data = eval("(" + responseText + ")");
if(data.response.error==0)
{
var newEventId = data.response.newEvent[0].event_id;
var strEventBoxId = Presentation.currentEventBoxId();
Presentation.resetEventBoxIdPosition(strEventBoxId,selDate);
var eventElem = $("#"+strEventBoxId);
eventElem.effect("highlight", {}, 2000);
eventElem.removeAttr("id");
eventElem.attr("id","UserEvent_"+newEventId);
Presentation.alertMessage(data.response.message);
}
else
{
Presentation.alertMessage(data.response.message);
Presentation.resetEventBoxIdPosition(Presentation.currentEventBoxId(),"");
}
Presentation.showHideMyReminderPanel(false);
},
// Being called on failure of method : submitEventData
submitEventDataFailure:function()
{
Presentation.alertMessage("Error Occured!");
Presentation.resetEventBoxIdPosition(Presentation.currentEventBoxId(),"");
},
// Retrive event data async call
retriveEventDetails: function(eventBoxId,eventId,selDate)
{
Presentation.appendMessage(eventBoxId,
"Wait...");
$.ajax({type:"POST",
url: "asyncHandler/handlerEvents.ashx",
data: "act=getEventDetails&eventId=" + eventId,
success:function(serverResponseData)
{
EventCallBack.retriveEventDetailsSuccess(serverResponseData,selDate,eventBoxId);
},
error: function(reqObject,typeofError,exceptionObj)
{
EventCallBack.retriveEventDetailsFailure(eventBoxId);
},
complete: function()
{
Presentation.removeMessage(eventBoxId);
}
});
},
// Being called on success of method : retriveEventDetails
retriveEventDetailsSuccess:function(responseText,selDate,eventBoxId)
{
data = eval("(" + responseText + ")");
if(data.response.error==0)
{
Presentation.generateMyReminderPanelForEdit(data.response.table,
selDate,
eventBoxId);
}
else
{
Presentation.showHideMyReminderPanel(false);
Presentation.alertMessage(data.response.message);
var selDate = $("#"+eventBoxId).attr("currentdate") || "";
Presentation.resetEventBoxIdPosition(eventBoxId,selDate);
}
},
// Being called on failure of method : retriveEventDetails
retriveEventDetailsFailure:function(eventBoxId)
{
Presentation.alertMessage("Error occored while processing request on server!");
},
// Update event async call
updateEvent: function(eventBoxId,templateId,selDate)
{
if($("#myReminderPanel_isActive").val()=="yes")
{
Presentation.appendMessage("myReminderFormPanel",
"Please Wait...");
var frequencyOption = "";
$("#myReminderPanel_EventFreq_Panel > select option:selected").each(function () {
if(frequencyOption.length>0)
{
frequencyOption += $(this).text() + ",";
}
else
{
frequencyOption = $(this).text();
}
});
var reminderOption = "";
$("#myReminderPanel_EventReminder_Panel > select option:selected").each(function () {
if(reminderOption.length>0)
{
reminderOption += $(this).text() + ",";
}
else
{
reminderOption = $(this).text();
}
});
var SelectedDate = $("#myReminderPanel_EventDate").val();
var disableEmailReminder = false;
if(Elem("myReminderPanel_EventDisableEmailReminder"))
{
disableEmailReminder = Elem("myReminderPanel_EventDisableEmailReminder").checked;
}
var disableSMSReminder = false;
if(Elem("myReminderPanel_EventDisableSMSReminder"))
{
disableSMSReminder = Elem("myReminderPanel_EventDisableSMSReminder").checked;
}
$.ajax({type:"POST",
url: "asyncHandler/handlerEvents.ashx",
data: "act=updateEvent"
+ "&eventId=" + $("#myReminderPanel_EditEventId").val()
+ "&tempId=" + $("#myReminderPanel_EventTemplateId").val()
+ "&eventTitle=" + $("#myReminderPanel_EventTitle").val()
+ "&eventDate=" + SelectedDate
+ "&eventFreq=" + frequencyOption
+ "&eventReminder=" + reminderOption
+ "&disableEmailReminder=" + disableEmailReminder
+ "&disableSMSReminder=" + disableSMSReminder
+ "&eventAltEmail=" + $("#myReminderPanel_EventAltEmail").val()
+ "&eventAltMobile=" + $("#myReminderPanel_EventAltMobile").val(),
success:function(serverResponseData)
{
EventCallBack.updateEventSuccess(serverResponseData,SelectedDate,eventBoxId);
},
error: function(reqObject,typeofError,exceptionObj)
{
EventCallBack.updateEventFailure(eventBoxId);
},
complete: function()
{
Presentation.removeMessage("myReminderFormPanel");
}
});
}
},
// Being called on success of method : updateEvent
updateEventSuccess:function(responseText,selDate,eventBoxId)
{
data = eval("(" + responseText + ")");
var strEventBoxId = Presentation.currentEventBoxId();
if(data.response.error==0)
{
$("#"+strEventBoxId).attr("currentdate",selDate);
Presentation.resetEventBoxIdPosition(strEventBoxId,selDate);
$("#"+strEventBoxId).effect("highlight", {}, 2000);
Presentation.alertMessage(data.response.message);
}
else
{
Presentation.alertMessage(data.response.message);
var boxselDate = $("#"+strEventBoxId).attr("currentdate") || "";
Presentation.resetEventBoxIdPosition(strEventBoxId,boxselDate);
}
Presentation.showHideMyReminderPanel(false);
},
// Being called on failure of method : updateEvent
updateEventFailure:function(eventBoxId)
{
Presentation.alertMessage("Error Occured!");
var selDate = $("#"+eventBoxId).attr("currentdate") || "";
Presentation.resetEventBoxIdPosition(eventBoxId,selDate);
}
}
// This class manages presentation of calendar.
// Drag drop and initilization of dragdrop is handled by init function
var Presentation = {
// Initializes events and drag drop
init:function()
{
$.preloadImages("Images/throbber.gif");
Presentation.initDragDrop();
$("#myReminderPanel_Close").bind("click",
Presentation.cancleAction);
$("#eventCalendar").after("<div id=\"alertMessage\" class=\"alertMessage\" style=\"width:350px;display:none;\"></div>");
$(".calEvent").bind("click",
function(){
if($(this).attr("currentdate"))
{
if($("#myReminderPanel_isActive").val()!="yes")
{
Presentation.onDropFunction(this.id,
"dv"+$(this).attr("currentdate"),
true);
}
}
});
},
alertMessage:function(msg)
{
var alertMessageDiv=$("#alertMessage");
if(alertMessageDiv)
{
alertMessageDiv.text(msg);
}
alertMessageDiv.fadeIn(1000).fadeOut(3000)
},
refreshEventBox:function(idOfDroppedElement)
{
var eventBoxId = Presentation.currentEventBoxId();
if(eventBoxId!="" && eventBoxId!=idOfDroppedElement)
{
if(Presentation.isEditEvent())
{
var selDate = $("#"+eventBoxId).attr("currentdate");
Presentation.resetEventBoxIdPosition(eventBoxId,
selDate);
}
else
{
Presentation.resetEventBoxIdPosition(eventBoxId,
"");
}
}
},
cancleAction: function()
{
Presentation.refreshEventBox();
Presentation.refreshEventPanel();
Presentation.showHideMyReminderPanel(false);
},
// Fuction being called on drop of event box
onDropFunction:function(droppedElement,idOfDateElement,flag)
{
var idOfDroppedElement = "";
if(flag)
{
idOfDroppedElement = droppedElement;
}
else
{
idOfDroppedElement = droppedElement[0].id;
}
//Not required, because drag is disabled when add/edit form is open
//Presentation.refreshEventBox(idOfDroppedElement);
if ("#"+idOfDateElement != Properties.eventContainerBoxId)
{
if(idOfDroppedElement.indexOf('EventTemplateId_')>=0) // Add event
{
EventCallBack.retriveEventTemplateDetais(idOfDroppedElement,
idOfDroppedElement.replace('EventTemplateId_',''),
idOfDateElement.replace('dv',''));
Presentation.refreshEventPanel();
}
else // Edit Event
{
EventCallBack.retriveEventDetails(idOfDroppedElement,
idOfDroppedElement.replace('UserEvent_',''),
idOfDateElement.replace('dv',''));
}
}
else
{
Presentation.showHideMyReminderPanel(false);
}
},
// Init funciton for dragdrop
initDragDrop: function() {
$(Properties.currentDayBoxClass).droppable({
accept: Properties.eventBoxClass,
drop: function(ev, ui) {
$(this).append($(ui.draggable));
Presentation.onDropFunction($(ui.draggable),this.id);
}
});
$(Properties.eventContainerBoxId).droppable({
accept: Properties.eventBoxClass,
drop: function(ev, ui) {
$(this).append($(ui.draggable));
Presentation.onDropFunction($(ui.draggable),this.id);
}
});
$(Properties.eventBoxClass).draggable({
helper:'clone',
opacity:0.5
});
},
// Removes previously created message box
removeMessage: function(targetElementId,postfix)
{
postfix = postfix || "msg";
$("#"+targetElementId+"_" + postfix).remove();
},
// Appends message box to given element by id and with options
appendMessage: function(targetElementId,text,msgDivPostfix,containerClass,messageElementClass)
{
msgDivPostfix = msgDivPostfix || "msg";
containerClass = containerClass || "loaderContainer";
messageElementClass = messageElementClass || "waitMessage";
if($("#"+targetElementId+"_"+msgDivPostfix).length>0)
{
Presentation.removeMessage(targetElementId,
msgDivPostfix);
}
$("#"+targetElementId).prepend("<div title=\""+text+"\" class=\""+containerClass+"\" id=\""+ targetElementId + "_" + msgDivPostfix +"\"><span class=\""+messageElementClass+"\">"+text+"</span></div>");
},
// Refreshes event panle, to check whether more events available or not
refreshEventPanel:function()
{
if($("#events div").length==0)
{
if($("#dvNoEventAvailableMessage").length==0)
{
$("#events").append("<div id=\"dvNoEventAvailableMessage\" class=\"alertMessage\" title=\"No more events..!\">No more events available</div>")
}
}
else
{
$("#dvNoEventAvailableMessage").remove();
}
},
// Sets visibility of event form
showHideMyReminderPanel :function(show)
{
if(show)
{
$("#myReminderPanel").show();
$("#myReminderPanel_isActive").val("yes");
$(Properties.eventBoxClass).draggable("disable");
$(Properties.eventBoxClass).css({cursor:"text"});
}
else
{
$("#myReminderPanel").hide();
$("#myReminderPanel_isActive").val("no");
$(Properties.eventBoxClass).draggable("enable");
$(Properties.eventBoxClass).css({cursor:"move"});
}
},
// Generates Event's form using json data retrived from server
generateMyReminderPanel :function(templateData,dateOfEvent,eventBoxId)
{
if(templateData)
{
if(templateData.length>0)
{
var currentTemplate = templateData[0];
Presentation.showHideMyReminderPanel(true);
Presentation.switchSubmitButtonActionForEdit(false);
$("#myReminderPanel_Header").html("Event details");
$("#myReminderPanel_Submit").val("Save");
Presentation.currentEventBoxId(eventBoxId);
$("#myReminderPanel_EventDate").val(dateOfEvent);
$("#myReminderPanel_EventFreq").val(currentTemplate.event_template_frequency);
$("#myReminderPanel_EventReminder").val(currentTemplate.event_template_reminder);
$("#myReminderPanel_EventFreq_Panel > select option:first-child").attr("selected","true");
$("#myReminderPanel_EventReminder_Panel > select option:first-child").attr("selected","true");
if(Elem("myReminderPanel_EventDisableEmailReminder"))
{
Elem("myReminderPanel_EventDisableEmailReminder").checked=(currentTemplate.event_template_email=="y");
}
if(Elem("myReminderPanel_EventDisableSMSReminder"))
{
Elem("myReminderPanel_EventDisableSMSReminder").checked=(currentTemplate.event_template_sms=="y");
}
$("#myReminderPanel_EventTitle").val(currentTemplate.event_template_name);
$("#myReminderPanel_EventTemplateId").val(currentTemplate.event_template_id);
if(currentTemplate.event_template_account_def_time!="y")
{
$("#myReminderPanel_EventReminder_Panel").hide();
}
else
{
$("#myReminderPanel_EventReminder_Panel").show();
}
if(currentTemplate.event_template_email!="y")
{
$("#myReminderPanel_EventDisableEmailReminder_Panel").hide();
}
else
{
$("#myReminderPanel_EventDisableEmailReminder_Panel").show();
}
if(currentTemplate.event_template_sms!="y")
{
$("#myReminderPanel_EventDisableSMSReminder_Panel").hide();
}
else
{
$("#myReminderPanel_EventDisableSMSReminder_Panel").show();
}
if(currentTemplate.event_template_alt_email!="y")
{
$("#myReminderPanel_EventAltEmail_Panel").hide();
}
else
{
$("myReminderPanel_EventAltEmail_Panel").show();
}
if(currentTemplate.event_template_alt_mobile!="y")
{
$("#myReminderPanel_EventAltMobile_Panel").hide();
}
else
{
$("#myReminderPanel_EventAltMobile_Panel").show();
}
$("#myReminderPanel_EventTitle").focus();
}
}
},
isEditEvent:function()
{
return $("#myReminderPanel_EditEventId").val()!="";
},
currentEventBoxId:function(value)
{
if(value)
{
$("#myReminderPanel_currentEventBoxId").val(value);
}
return $("#myReminderPanel_currentEventBoxId").val();
},
switchSubmitButtonActionForEdit:function(flag,eventId)
{
eventId = eventId || "";
$("#myReminderPanel_Submit").unbind("click",
EventCallBack.updateEvent);
$("#myReminderPanel_Submit").unbind("click",
EventCallBack.submitEventData);
$("#myReminderPanel_EditEventId").val(eventId);
if(flag)
{
$("#myReminderPanel_EventDate_Panel_Edit").show();
$("#myReminderPanel_Submit").bind("click",
EventCallBack.updateEvent);
}
else
{
$("#myReminderPanel_EventDate_Panel_Edit").hide();
$("#myReminderPanel_Submit").bind("click",
EventCallBack.submitEventData);
}
},
// Generates Event's form for edit using json data retrived from server
generateMyReminderPanelForEdit : function(eventData,dateOfEvent,eventBoxId)
{
if(eventData)
{
if(eventData.length>0)
{
var currentEvent = eventData[0];
Presentation.showHideMyReminderPanel(true);
Presentation.switchSubmitButtonActionForEdit(true,
eventBoxId.replace('UserEvent_',''));
$("#myReminderPanel_Header").html("Edit Event details");
$("#myReminderPanel_Submit").val("Update");
Presentation.currentEventBoxId(eventBoxId);
$("#myReminderPanel_EventDate").val(dateOfEvent);
$("#myReminderPanel_EventDateEdit").html(currentEvent.converteddate);
$("#myReminderPanel_EventFreq").val(currentEvent.event_frequency);
$("#myReminderPanel_EventReminder").val(currentEvent.event_reminder);
$("#myReminderPanel_EventFreq_Panel > select option").each(function(){
if($(this).attr("value")==currentEvent.event_frequency)
{
$(this).attr("selected","true");
}
});
$("#myReminderPanel_EventReminder_Panel > select option").each(function(){
if($(this).attr("value")==currentEvent.event_reminder)
{
$(this).attr("selected","true");
}
});
if(Elem("myReminderPanel_EventDisableEmailReminder"))
{
Elem("myReminderPanel_EventDisableEmailReminder").checked=(currentEvent.event_email=="y");
}
if(Elem("myReminderPanel_EventDisableSMSReminder"))
{
Elem("myReminderPanel_EventDisableSMSReminder").checked=(currentEvent.event_sms=="y");
}
$("#myReminderPanel_EventTitle").val(currentEvent.event_title);
$("#myReminderPanel_EventTemplateId").val(currentEvent.event_template_id);
$("#myReminderPanel_EventTitle").focus();
$("#myReminderPanel_EventReminder_Panel").show();
$("#myReminderPanel_EventDisableEmailReminder_Panel").show();
$("#myReminderPanel_EventDisableSMSReminder_Panel").show();
$("#myReminderPanel_EventAltEmail_Panel").show();
$("#myReminderPanel_EventAltMobile_Panel").show();
}
}
},
resetEventBoxIdPosition:function(eventBoxId,selDate)
{
if(selDate=="")
{
if(Elem(eventBoxId))
{
var selDate = $("#"+eventBoxId).attr("currentdate") || "";
if(selDate.length==0)
{
Elem("events").appendChild(Elem(eventBoxId));
Presentation.currentEventBoxId("");
$("#myReminderPanel_EditEventId").val("");
}
}
}
else
{
var currentDateId = $("#"+eventBoxId).parent().get(0).id;
if(currentDateId != "dv" + selDate)
{
if(Elem("dv" + selDate))
{
if(Elem(eventBoxId))
{
Elem("dv" + selDate).appendChild(Elem(eventBoxId));
Presentation.currentEventBoxId("");
$("#myReminderPanel_EditEventId").val("");
}
}
else
{
if(selDate==undefined)
{
Presentation.alertMessage("error occured, Selected date not valid")
}
else
{
Presentation.alertMessage("Event is saved. Date selected is not in current month so it will not be visible")
Elem(eventBoxId).parentNode.removeChild(Elem(eventBoxId));
}
}
}
}
}
}
Untitled JavaScript (6-Aug @ 09:59)
Syntax Highlighted Code
- hello there {
- can you read me();
- }
Plain Code
hello there {
can you read me();
}
Untitled JavaScript (6-Aug @ 02:13)
Syntax Highlighted Code
- http://remysharp.com/visual-jquery/
Plain Code
http://remysharp.com/visual-jquery/
Untitled JavaScript (5-Aug @ 07:50)
Syntax Highlighted Code
- (function () {
- var blank_iframe = '/index-blank.html';
- var example_jquery = 'http://ajax.googleapis.com/ajax/libs/jquery/1.2.6/jquery.min.js'; // latest from google
- [386 more lines...]
Plain Code
(function () {
var blank_iframe = '/index-blank.html';
var example_jquery = 'http://ajax.googleapis.com/ajax/libs/jquery/1.2.6/jquery.min.js'; // latest from google
var re_opt = /options/i;
if (!window.jquerydocs) window.jquerydocs = {};
if (!window.xmldoc) window.xmldoc = null;
window.loadDocs = function(data) {
$(document).trigger('api-loading');
if (!xmldoc && typeof data != "undefined") {
jquerydocs = data;
attachFind(jquerydocs);
$(document).trigger('api-load-success');
$(document).trigger('api-load-complete');
} else {
// parser
$.ajax({
url: xmldoc || 'jquery-docs.xml', // generated from jquery source: /tools/wikiapi2xml/createjQueryXMLDocs.py
dataType: 'xml',
success: parse,
error: function () {
$(document).trigger('api-load-error');
},
complete: function () {
$(document).trigger('api-load-complete');
}
});
}
};
function parse(xml) {
var docinfo = $('docs', xml);
var guid = 0; // TODO upgrade guid to a combo of fn name and params - like Jorn's browser
jquerydocs.version = docinfo.attr('version');
jquerydocs.timestamp = docinfo.attr('timestamp');
jquerydocs.startdoc = docinfo.attr('startdoc');
var letters = []; // holder before sorting and inserting
jquerydocs.letters = [];
jquerydocs.data = {};
jquerydocs.searchNames = [];
jquerydocs.categories = [];
// loop through all types collecting data
$('cat', xml).each(function (i) {
var catName = this.getAttribute('value');
var category = {};
category.name = catName;
category.subcategories = [];
$('subcat', this).each(function (i) {
var subcatName = this.getAttribute('value');
category.subcategories.push(subcatName);
$('function,property,selector', this).each(function () {
var data = {};
guid++;
// some function names have spaces around them - so trim
var name = this.getAttribute('name').replace( /^\s+|\s+$/g, '');
var searchName = name.toLowerCase().replace(/^jquery\./, '');
letters.push(name.toLowerCase().substr(0,1));
name = name.replace(/^jquery\./i, '$.');
jquerydocs.searchNames.push(searchName + guid);
data['id'] = guid;
data['searchname'] = searchName;
data['name'] = name;
data['type'] = this.nodeName.toLowerCase();
data['category'] = this.getAttribute('cat');
data['subcategory'] = subcatName;
data['return'] = escapeHTML(this.getAttribute('return'));
data['added'] = $('added', this).text();
data['sample'] = $('> sample', this).text();
data['desc'] = $('> desc', this).text();
data['longdesc'] = deWikify($('> longdesc', this).text());
// silly hack because of conversion issue from wiki to text (the .ready function
// has HTML in the description), but also includes HTML that should be printed,
// in particular the body tag :-(
data.longdesc = data.longdesc.replace(/<body>/, '<body>');
// some descs are in HTML format, some aren't
if (!(/<p>/).test(data.longdesc)) {
data.longdesc = '<p>' + data.longdesc.split(/\n\n/).join('</p><p>') + '</p>';
}
// strip our empty p tag if there was no description
if (data.longdesc == '<p></p>') {
data.longdesc = '';
}
/** params - we'll also search for Options to decide whether we need to parse */
var readOptions = false;
data.params = [];
$('params', this).each(function (i) {
var type = escapeHTML(this.getAttribute('type'));
var name = this.getAttribute('name');
var opt = this.getAttribute('optional') || "";
var desc = $('desc', this).text();
if (re_opt.test(type)) {
readOptions = true;
}
data.params.push({
optional : (/true/i).test(opt), // bool
name : name,
type : type,
desc : desc
});
});
if (readOptions) {
data.options = [];
$('option', this).each(function () {
var option = {};
option['name'] = this.getAttribute('name');
option['default'] = this.getAttribute('default') || '';
option['type'] = escapeHTML(this.getAttribute('type'));
option['desc'] = deWikify($('desc', this).text());
data.options.push(option);
});
}
data.examples = [];
/** examples */
$('example', this).each(function (i) {
var iframe = '', exampleId = '';
var example = {};
example['code'] = $('code', this).text();
example['htmlCode'] = escapeHTML(example.code);
example['desc'] = deWikify(escapeHTML($('desc', this).text()));
example['css'] = $('css', this).text() || '';
example['inhead'] = $('inhead', this).text() || '';
example['html'] = $('html', this).text() || '';
exampleId = guid + 'iframeExample' + i;
example['exampleId'] = exampleId;
if (example.html) {
iframe = '<iframe id="' + exampleId + '" class="example" src="' + blank_iframe + '"></iframe>';
// we're storing the example iframe source to insert in to
// the iframe only once it's inserted in to the DOM.
example['runCode'] = iframeTemplate().replace(/%([a-z]*)%/ig, function (m, l) {
return example[l] || "";
});
} else {
example.runCode = '';
}
data.examples.push(example);
});
jquerydocs.data[searchName + data.id] = data;
});
});
jquerydocs.categories.push(category); // FIXME should I warn if this exists?
});
jquerydocs.letters = unique($.map(letters.sort(), function (i) {
return i.substr(0,1);
}));
// attachFind(jquerydocs);
$(document).trigger('api-load-success');
}
// helpers
function attachFind(o) {
o.find = function (s, by) {
var found = [],
tmp = {},
tmpNames = [],
lettersLK = {},
letters = [],
catsLK = {},
cats = [],
catPointer = 0,
subLK = {},
sub = [],
data = {};
var i = 0;
s = s.toLowerCase();
by = (by || 'searchname').toLowerCase();
if (by == 'name') by = 'searchname'; // search without the $.
for (i = 0; i < jquerydocs.searchNames.length; i++) {
if (jquerydocs.data[jquerydocs.searchNames[i]][by] && jquerydocs.data[jquerydocs.searchNames[i]][by].toLowerCase().indexOf(s) == 0) {
data = tmp[jquerydocs.searchNames[i]] = jquerydocs.data[jquerydocs.searchNames[i]];
tmpNames.push(jquerydocs.searchNames[i]);
if (!lettersLK[jquerydocs.searchNames[i].substr(0, 1)]) {
lettersLK[jquerydocs.searchNames[i].substr(0, 1)] = true;
letters.push(jquerydocs.searchNames[i].substr(0, 1));
}
if (typeof catsLK[data.category] == 'undefined') {
catsLK[data.category] = catPointer;
cats.push({ name : data.category, subcategories : [] });
catPointer++;
}
if (!subLK[data.subcategory]) {
subLK[data.subcategory] = true;
cats[catsLK[data.category]].subcategories.push(data.subcategory);
}
}
}
tmpNames = tmpNames.sort().reverse(); // never sure if this is faster with the reverse
i = tmpNames.length;
while (i--) {
found.push(tmp[tmpNames[i]]);
}
// this is kind of noddy, but returns the same object as we queried - which is cool!
found.letters = letters;
found.categories = cats;
found.data = tmp;
found.searchNames = tmpNames;
attachFind(found);
return found;
};
}
function fieldMap() {
return {
}
}
function unique(a) {
var ret = [], done = {};
try {
for ( var i = 0, length = a.length; i < length; i++ ) {
var id = a[ i ] ;
if ( !done[ id ] ) {
done[ id ] = true;
ret.push( a[ i ] );
}
}
} catch( e ) {
ret = a;
}
return ret;
}
function iframeTemplate() {
// array so that we maintain some formatting
return [
'<!' + 'DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN"',
' "http://www.w3.org/TR/html4/loose.dtd">',
'<' + 'html>',
'<' + 'head>',
'<base href="http://docs.jquery.com" />',
'<' + 'script src="' + example_jquery + '"><' + '/script>',
'%inhead%',
'<' + 'script>',
'$(document).ready(function(){', '%code%', ' });',
'<' + '/script>',
'<' + 'style>',
'%css%',
'<' + '/style>',
'<' + '/head>',
'<' + 'body>',
'%html%',
'<' + '/body>',
'<' + '/html>'
].join("\n");
}
/** public utility functions */
window.escapeHTML = function (s) {
// converts null to string
return (s+"").replace(/[<>]/g, function (m) {
if (m == '<') return '<';
else if (m == '>') return '>';
});
};
window.cleanSelector = function(s) {
return (s+"").replace(/[\$\.]/g, function (m) {
// handle escaping characters that break the selector engine
if (m == '$') {
return '\\$';
} else if (m == '.') {
return '\\.';
}
});
};
window.linkifyTypes = function(type) {
// cheeky way to avoid doing a massive if (m == x || m == y || m == etc) - we just do an .indexOf()
var nodocs = '|jQuery|XMLHttpRequest|Plugins|Validator|Validation|undefined|or|Any|DOM|Map|top|left|lt|gt|\(s\)||'; // note we purposely include an empty match
return type ? $.map(type.replace(/DOMElement/g, 'DOM Element').split(/, /), function (n) {
// match words and linkify, then italic to the optionals
return n.replace(/boolean/, 'Boolean').replace(/\b[a-z]*\b/gi, function (m, l) {
// special case
if (m == 'Elements') {
return '<a href="http://docs.jquery.com/Types#Element">Element</a>s';
// no specific documentation for these types
} else if (nodocs.indexOf('|' + m + '|') !== -1) {
return m;
} else {
return '<a href="http://docs.jquery.com/Types#' + m + '">' + m + '</a>';
}
});
}).join(', ') : "";
};
window.deWikify = function (s) {
return (""+s).replace(/'''.*?'''/g, function (m) {
return '<strong>' + m.replace(/'''/g, '') + '</strong>';
}).replace(/''.*?''/g, function (m) {
return '<em>' + m.replace(/''/g, '') + '</em>';
}).replace(/\[http.*?\]/, function (m) {
var p = m.replace(/^\[/, '').replace(/\]$/, '').split(/ /);
return '<a href="' + p[0] + '">' + (p.length == 2 ? p[1] : p[0]) + '</a>';
}).replace(/(((^|\n)(\*|[0-9]+.).*)+)/g, function (m) {
var type = 'ol';
// strip leading new line
m = m.replace( /^\s+|\s+$/g, "" );
if (m.match(/^\*/)) type = 'ul';
return '<' + type + '><li>' + m.replace(/\*?/g, '').split(/\n/).join("</li><li>") + '</li></' + type + '>';
});
};
window.runExample = function(data) {
if (!data.examples || data.examples.length == 0) return;
var i, win, example;
for (i = 0; i < data.examples.length; i++) {
example = data.examples[i];
win = $('#' + cleanSelector(example.exampleId)).get(0);
if (win) {
win = win.contentDocument || win.contentWindow.document;
// from docs.jquery.com
win.write(example.runCode.replace("$(document).ready(function(){", "window.onload = (function(){try{")
.replace(/}\);\s*<\/sc/, "}catch(e){}});</sc")
.replace("</head>", "<style>html,body{border:0; margin:0; padding:0;}</style></head>")
);
win.close();
}
}
};
window.fixLinks = function (context) {
// since the source comes from the wiki, we need to adjust some of the links
$('a', context).each(function () {
var href = this.getAttribute('href');
if (href && !href.match(/http/) && !href.match(/^#/) && this.className != 'fnName') {
this.host = 'docs.jquery.com';
this.pathname = this.pathname.replace(window.location.pathname, '');
}
});
};
})();
Untitled JavaScript (2-Aug @ 12:57)
Syntax Highlighted Code
- // Keep track of the direction of the drag for use during onDragOver
- var y = Event.getPageY(e);
- [7 more lines...]
Plain Code
// Keep track of the direction of the drag for use during onDragOver
var y = Event.getPageY(e);
if (y < this.lastY) {
this.goingUp = true;
} else if (y > this.lastY) {
this.goingUp = false;
}
this.lastY = y;
Untitled JavaScript (2-Aug @ 01:38)
Syntax Highlighted Code
- alert("stuff");
Plain Code
alert("stuff");
Untitled JavaScript (1-Aug @ 05:22)
Syntax Highlighted Code
- var newWhim = document.getElementById('menu_whim');
- if(newWhim){
- [4 more lines...]
Plain Code
var newWhim = document.getElementById('menu_whim');
if(newWhim){
var c = newWhim.cloneNode(true);
document.getElementById('blah').appendChild(c);
}
Untitled JavaScript (1-Aug @ 05:17)
Syntax Highlighted Code
- $('#daftar').click(function() {
- if ($("#userd").val() == '')
- {
- alert("Username belum di isi..!");
- [3 more lines...]
Plain Code
$('#daftar').click(function() {
if ($("#userd").val() == '')
{
alert("Username belum di isi..!");
document.frm_daftar.userd.focus();
return false;
}
Untitled JavaScript (30-Jul @ 09:23)
Syntax Highlighted Code
- // ==UserScript==
- // @name roosterteeth watchlistAlert
- // @namespace userscripts.org
- // @description roosterteeth watchlistAlert
- [31 more lines...]
Plain Code
// ==UserScript==
// @name roosterteeth watchlistAlert
// @namespace userscripts.org
// @description roosterteeth watchlistAlert
// @include http://www.roosterteeth.com*
// ==/UserScript==
if (document.getElementById('pageContent')){
GM_xmlhttpRequest({
method: 'GET',
url: 'http://www.roosterteeth.com/members/index.php',
onload: function(responseDetails) {
var rt = responseDetails.responseText;
if(!rt.match('You have no new alerts')){
var s = rt.split("id='Watching'>")[1].split("</div>")[0];
var nT = document.createElement('table');
nT.setAttribute('width','100%');
nT.innerHTML = "<div id='Watching'>"+s+"</div>";
var par = document.getElementById('shadow3');
par.insertBefore(nT, par.firstChild);
}
},
onerror: function(responseDetails) {
alert('summin broke '+responseDetails.responseText);
}
});
}
Untitled JavaScript (29-Jul @ 20:43)
Syntax Highlighted Code
- function getWeatherFeed() {
- $.ajax({
- url: 'http://web18.accuweather.com/widget/weatheralarm/weatheralarm.asp?location=16801',
- type: 'GET',
- [55 more lines...]
Plain Code
function getWeatherFeed() {
$.ajax({
url: 'http://web18.accuweather.com/widget/weatheralarm/weatheralarm.asp?location=16801',
type: 'GET',
dataType: 'xml',
timeout: 2000,
beforeSend: function() {},
error: function(e) {
$('#widget').css('background', 'green');
$('#temp').html(e);
},
success: function(xml) {
currentCity = $(xml).find('city').text();
currentState = $(xml).find('state').text();
currentIcon = $(xml).find('weathericon:first').text();
currentTemp = $(xml).find('temp').text();
currentHigh = $(xml).find('high:first').text();
currentLow = $(xml).find('low:first').text();
alertTotal = $(xml).find('alerttotal').text();
alertURL = $(xml).find('url').slice(1, 2).text();
numAlarms = $(xml).find('numalarms').text();
numAlerts = $(xml).find('alerttotal').text();
var i = 0;
$(xml).find('alarm').each(function() {
alarmType[i] = $(this).find('type').text()
alarmNumDays[i] = $(this).find('numdays').text();
alarmDay[i] = new Array();
alarmDayURL[i] = new Array();
var z = 0;
$(this).find('day').each(function() {
alarmDay[i][z] = $(this).text();
alarmDayURL[i][z] = $(this).attr('url');
z++;
});
i++;
});
var i = 0;
$(xml).find('alert').each(function() {
alertURL = $(this).find('url').text();
alertDescrip[i] = $(this).find('description').text();
i++;
});
if (currentState.length > 2) {
isInternational = true;
} else {
isInternational = false;
}
updateConditions();
}
});
}
function updateConditions() {
$('#temp').html(currentTemp);
}
Untitled JavaScript (28-Jul @ 10:24)
Syntax Highlighted Code
- // jslint.js
- // 2008-07-25
- /*
- Copyright (c) 2002 Douglas Crockford (www.JSLint.com)
- [1677 more lines...]
Plain Code
// jslint.js
// 2008-07-25
/*
Copyright (c) 2002 Douglas Crockford (www.JSLint.com)
Permission is hereby granted, free of charge, to any person obtaining a copy of
this software and associated documentation files (the "Software"), to deal in
the Software without restriction, including without limitation the rights to
use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies
of the Software, and to permit persons to whom the Software is furnished to do
so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.
The Software shall be used for Good, not Evil.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.
*/
/*
JSLINT is a global function. It takes two parameters.
var myResult = JSLINT(source, option);
The first parameter is either a string or an array of strings. If it is a
string, it will be split on '\n' or '\r'. If it is an array of strings, it
is assumed that each string represents one line. The source can be a
JavaScript text, or HTML text, or a Konfabulator text.
The second parameter is an optional object of options which control the
operation of JSLINT. Most of the options are booleans: They are all are
optional and have a default value of false.
If it checks out, JSLINT returns true. Otherwise, it returns false.
If false, you can inspect JSLINT.errors to find out the problems.
JSLINT.errors is an array of objects containing these members:
{
line : The line (relative to 0) at which the lint was found
character : The character (relative to 0) at which the lint was found
reason : The problem
evidence : The text line in which the problem occurred
raw : The raw message before the details were inserted
a : The first detail
b : The second detail
c : The third detail
d : The fourth detail
}
If a fatal error was found, a null will be the last element of the
JSLINT.errors array.
You can request a Function Report, which shows all of the functions
and the parameters and vars that they use. This can be used to find
implied global variables and other problems. The report is in HTML and
can be inserted in an HTML <body>.
var myReport = JSLINT.report(limited);
If limited is true, then the report will be limited to only errors.
*/
/*jslint evil: true, nomen: false */
/*members "\b", "\t", "\n", "\f", "\r", "\"", "(begin)", "(breakage)",
"(context)", "(end)", "(global)", "(identifier)", "(line)", "(loopage)",
"(name)", "(params)", "(scope)", "(verb)", ")", "++", "--", "\/",
ADSAFE, Array, Boolean, COM, Canvas, CustomAnimation, Date, Debug, E,
Error, EvalError, FadeAnimation, FormField, Frame, Function, HotKey,
Image, JSON, LN10, LN2, LOG10E, LOG2E, MAX_VALUE, MIN_VALUE, Math,
MenuItem, MoveAnimation, NEGATIVE_INFINITY, Number, Object, Option, PI,
POSITIVE_INFINITY, Point, RangeError, ReferenceError, RegExp,
RotateAnimation, SQRT1_2, SQRT2, ScrollBar, String, SyntaxError, System,
Text, TextArea, Timer, TypeError, URIError, URL, Window, XMLDOM,
XMLHttpRequest, "\\", "]", a, abbr, "about-box", "about-image",
"about-text", "about-version", acronym, action, address, adsafe, alert,
alignment, anchorstyle, animator, appleScript, applet, apply, approved,
area, arguments, author, autohide, b, background, base, bdo, beep,
create, bgcolor, bgcolour, bgopacity, big, bitwise, block, blockquote,
blur, body, br, browser, button, bytesToUIString, c, call, callee,
caller, canvas, cap, caption, cases, center, charAt, charCodeAt,
character, charset, checked, chooseColor, chooseFile, chooseFolder,
cite, clearInterval, clearTimeout, cliprect, close, closeWidget, closed,
code, col, colgroup, color, colorize, colour, columns, comment, company,
condition, confirm, console, constructor, content, contextmenuitems,
convertPathToHFS, convertPathToPlatform, copyright, d, data, dd, debug,
decodeURI, decodeURIComponent, defaultStatus, defaulttracking,
defaultvalue, defineClass, del, description, deserialize, dfn, dir,
directory, div, dl, doAttribute, doBegin, doIt, doTagName, document, dt,
dynsrc, editable, em, embed, empty, enabled, encodeURI,
encodeURIComponent, entityify, eqeqeq, errors, escape, eval, event,
evidence, evil, exec, exps, extension, fieldset, file, filesystem,
fillmode, first, floor, focus, focusWidget, font, fontstyle, forin,
form, fragment, frame, frames, frameset, from, fromCharCode, fud,
function, g, gc, getComputedStyle, group, h1, h2, h3, h4, h5,
h6, halign, handlelinks, hasOwnProperty, head, height, help, hidden,
history, hlinesize, hoffset, hotkey, hr, href, hregistrationpoint,
hscrollbar, hsladjustment, hsltinting, html, i, iTunes, icon, id,
identifier, iframe, image, img, include, indent, indexOf, init, input,
ins, interval, isAlpha, isApplicationRunning, isDigit, isFinite, isNaN,
join, kbd, key, kind, konfabulatorVersion, label, labelled, laxbreak,
lbp, led, left, legend, length, level, li, line, lines, link, load,
loadClass, loadingsrc, location, locked, log, lowsrc, m, map, match,
max, maxlength, menu, menuitem, message, meta, min, minimumversion,
minlength, missingsrc, modifier, moveBy, moveTo, name, navigator, new,
noframes, nomen, noscript, notsaved, nud, object, ol, on, onblur,
onclick, oncontextmenu, ondragdrop, ondragenter, ondragexit, onerror,
onfirstdisplay, onfocus, ongainfocus, onimageloaded, onkeydown,
onkeypress, onkeyup, onload, onlosefocus, onmousedown, onmousedrag,
onmouseenter, onmouseexit, onmousemove, onmouseup, onmousewheel,
onmulticlick, onresize, onselect, ontextinput, ontimerfired, onunload,
onvaluechanged, opacity, open, openURL, opener, opera, optgroup, option,
optionvalue, order, orientation, p, pagesize, param, parent, parseFloat,
parseInt, passfail, play, plusplus, pop, popupMenu, pre, predef,
preference, preferenceGroups, preferencegroup, preferences, print,
prompt, prototype, push, q, quit, random, raw, reach, readFile, readUrl,
reason, regexp, reloadWidget, remoteasync, replace, report,
requiredplatform, reserved, resizeBy, resizeTo, resolvePath,
resumeUpdates, rhino, right, root, rotation, runCommand, runCommandInBg,
safe, samp, saveAs, savePreferences, screen, script, scroll, scrollBy,
scrollTo, scrollbar, scrolling, scrollx, scrolly, seal, search, secure,
select, self, serialize, setInterval, setTimeout, setting, settings,
shadow, shift, showWidgetPreferences, sidebar, size, skip, sleep, slice,
small, sort, span, spawn, speak, special, spellcheck, split, src,
srcheight, srcwidth, status, strong, style, sub, substr, subviews, sup,
superview, supplant, suppressUpdates, sync, system, table, tag, tbody,
td, tellWidget, test, text, textarea, tfoot, th, thead, thumbcolor,
ticking, ticklabel, ticks, tileorigin, timer, title, toLowerCase,
toString, toUpperCase, toint32, token, tooltip, top, tr, tracking,
trigger, truncation, tt, type, u, ul, undef, unescape, union, unwatch,
updateNow, url, usefileicon, valign, value, valueOf, var, version,
visible, vlinesize, voffset, vregistrationpoint, vscrollbar, watch,
white, widget, width, window, wrap, yahooCheckLogin, yahooLogin,
yahooLogout, zorder
*/
/*global JSLINT*/
// We build the application inside a function so that we produce only a single
// global variable. The function will be invoked, its return value is the JSLINT
// application itself.
"use strict";
JSLINT = function () {
var adsafe_id, // The widget's ADsafe id.
adsafe_may, // The widget may load approved scripts.
adsafe_went, // ADSAFE.go has been called.
anonname, // The guessed name for anonymous functions.
approved, // ADsafe approved urls.
// These are members that should not be permitted in third party ads.
banned = { // the member names that ADsafe prohibits.
apply : true,
'arguments' : true,
call : true,
callee : true,
caller : true,
constructor : true,
'eval' : true,
prototype : true,
unwatch : true,
valueOf : true,
watch : true
},
// These are the JSLint boolean options.
boolOptions = {
adsafe : true, // if ADsafe should be enforced
bitwise : true, // if bitwise operators should not be allowed
browser : true, // if the standard browser globals should be predefined
cap : true, // if upper case HTML should be allowed
debug : true, // if debugger statements should be allowed
eqeqeq : true, // if === should be required
evil : true, // if eval should be allowed
forin : true, // if for in statements must filter
fragment : true, // if HTML fragments should be allowed
laxbreak : true, // if line breaks should not be checked
nomen : true, // if names should be checked
on : true, // if HTML event handlers should be allowed
passfail : true, // if the scan should stop on first error
plusplus : true, // if increment/decrement should not be allowed
regexp : true, // if the . should not be allowed in regexp literals
rhino : true, // if the Rhino environment globals should be predefined
undef : true, // if variables should be declared before used
safe : true, // if use of some browser features should be restricted
sidebar : true, // if the System object should be predefined
sub : true, // if all forms of subscript notation are tolerated
white : true, // if strict whitespace rules apply
widget : true // if the Yahoo Widgets globals should be predefined
},
// browser contains a set of global names which are commonly provided by a
// web browser environment.
browser = {
alert : true,
blur : true,
clearInterval : true,
clearTimeout : true,
close : true,
closed : true,
confirm : true,
console : true,
Debug : true,
defaultStatus : true,
document : true,
event : true,
focus : true,
frames : true,
getComputedStyle: true,
history : true,
Image : true,
length : true,
location : true,
moveBy : true,
moveTo : true,
name : true,
navigator : true,
onblur : true,
onerror : true,
onfocus : true,
onload : true,
onresize : true,
onunload : true,
open : true,
opener : true,
opera : true,
Option : true,
parent : true,
print : true,
prompt : true,
resizeBy : true,
resizeTo : true,
screen : true,
scroll : true,
scrollBy : true,
scrollTo : true,
self : true,
setInterval : true,
setTimeout : true,
status : true,
top : true,
window : true,
XMLHttpRequest : true
},
escapes = {
'\b': '\\b',
'\t': '\\t',
'\n': '\\n',
'\f': '\\f',
'\r': '\\r',
'"' : '\\"',
'/' : '\\/',
'\\': '\\\\'
},
funct, // The current function
functions, // All of the functions
href = {
background : true,
content : true,
data : true,
dynsrc : true,
href : true,
lowsrc : true,
src : true
},
global, // The global scope
ids, // HTML ids
implied, // Implied globals
inblock,
indent,
jsonmode,
lines,
lookahead,
member,
membersOnly,
nexttoken,
noreach,
option,
predefined, // Global variables defined by option
prereg,
prevtoken,
rhino = {
defineClass : true,
deserialize : true,
gc : true,
help : true,
load : true,
loadClass : true,
print : true,
quit : true,
readFile : true,
readUrl : true,
runCommand : true,
seal : true,
serialize : true,
spawn : true,
sync : true,
toint32 : true,
version : true
},
scope, // The current scope
sidebar = {
System : true
},
src,
stack,
// standard contains the global names that are provided by the
// ECMAScript standard.
standard = {
Array : true,
Boolean : true,
Date : true,
decodeURI : true,
decodeURIComponent : true,
encodeURI : true,
encodeURIComponent : true,
Error : true,
'eval' : true,
EvalError : true,
Function : true,
isFinite : true,
isNaN : true,
JSON : true,
Math : true,
Number : true,
Object : true,
parseInt : true,
parseFloat : true,
RangeError : true,
ReferenceError : true,
RegExp : true,
String : true,
SyntaxError : true,
TypeError : true,
URIError : true
},
standard_member = {
E : true,
LN2 : true,
LN10 : true,
LOG2E : true,
LOG10E : true,
PI : true,
SQRT1_2 : true,
SQRT2 : true,
MAX_VALUE : true,
MIN_VALUE : true,
NEGATIVE_INFINITY : true,
POSITIVE_INFINITY : true
},
syntax = {},
tab,
token,
urls,
warnings,
// widget contains the global names which are provided to a Yahoo
// (fna Konfabulator) widget.
widget = {
alert : true,
appleScript : true,
animator : true,
appleScript : true,
beep : true,
bytesToUIString : true,
Canvas : true,
chooseColor : true,
chooseFile : true,
chooseFolder : true,
closeWidget : true,
COM : true,
convertPathToHFS : true,
convertPathToPlatform : true,
CustomAnimation : true,
escape : true,
FadeAnimation : true,
filesystem : true,
focusWidget : true,
form : true,
FormField : true,
Frame : true,
HotKey : true,
Image : true,
include : true,
isApplicationRunning : true,
iTunes : true,
konfabulatorVersion : true,
log : true,
MenuItem : true,
MoveAnimation : true,
openURL : true,
play : true,
Point : true,
popupMenu : true,
preferenceGroups : true,
preferences : true,
print : true,
prompt : true,
random : true,
reloadWidget : true,
resolvePath : true,
resumeUpdates : true,
RotateAnimation : true,
runCommand : true,
runCommandInBg : true,
saveAs : true,
savePreferences : true,
screen : true,
ScrollBar : true,
showWidgetPreferences : true,
sleep : true,
speak : true,
suppressUpdates : true,
system : true,
tellWidget : true,
Text : true,
TextArea : true,
Timer : true,
unescape : true,
updateNow : true,
URL : true,
widget : true,
Window : true,
XMLDOM : true,
XMLHttpRequest : true,
yahooCheckLogin : true,
yahooLogin : true,
yahooLogout : true
},
// xmode is used to adapt to the exceptions in XML parsing.
// It can have these states:
// false .js script file
// " A " attribute
// ' A ' attribute
// content The content of a script tag
// CDATA A CDATA block
xmode,
// xtype identifies the type of document being analyzed.
// It can have these states:
// false .js script file
// html .html file
// widget .kon Konfabulator file
xtype,
// unsafe comment or string
ax = /@cc|<\/?script|\]\]|<!|</i,
// unsafe character
cx = /[\u0000-\u001f\u007f-\u009f\u00ad\u0600-\u0604\u070f\u17b4\u17b5\u200c-\u200f\u2028-\u202f\u2060-\u206f\ufeff\ufff0-\uffff]/,
// token
tx = /^\s*([(){}\[.,:;'"~]|\](\]>)?|\?>?|==?=?|\/(\*(global|extern|jslint|member|members)?|=|\/)?|\*[\/=]?|\+[+=]?|-[\-=]?|%[=>]?|&[&=]?|\|[|=]?|>>?>?=?|<([\/=%\?]|\!(\[|--)?|<=?)?|\^=?|\!=?=?|[a-zA-Z_$][a-zA-Z0-9_$]*|[0-9]+([xX][0-9a-fA-F]+|\.[0-9]*)?([eE][+\-]?[0-9]+)?)/,
// star slash
lx = /\*\/|\/\*/,
// identifier
ix = /^([a-zA-Z_$][a-zA-Z0-9_$]*)$/,
// javascript url
jx = /^(?:javascript|jscript|ecmascript|vbscript|mocha|livescript)\s*:/i,
// url badness
ux = /&|\+|\u00AD|\.\.|\/\*|%[^;]|base64|url|expression|data|mailto/i;
function F() {}
if (typeof Object.create !== 'function') {
Object.create = function (o) {
F.prototype = o;
return new F();
};
}
Object.prototype.union = function (o) {
var n;
for (n in o) {
if (o.hasOwnProperty(n)) {
this[n] = o[n];
}
}
};
String.prototype.entityify = function () {
return this.
replace(/&/g, '&').
replace(/</g, '<').
replace(/>/g, '>');
};
String.prototype.isAlpha = function () {
return (this >= 'a' && this <= 'z\uffff') ||
(this >= 'A' && this <= 'Z\uffff');
};
String.prototype.isDigit = function () {
return (this >= '0' && this <= '9');
};
String.prototype.supplant = function (o) {
return this.replace(/\{([^{}]*)\}/g, function (a, b) {
var r = o[b];
return typeof r === 'string' || typeof r === 'number' ? r : a;
});
};
String.prototype.name = function () {
// If the string looks like an identifier, then we can return it as is.
// If the string contains no control characters, no quote characters, and no
// backslash characters, then we can simply slap some quotes around it.
// Otherwise we must also replace the offending characters with safe
// sequences.
if (ix.test(this)) {
return this;
}
if (/[&<"\/\\\x00-\x1f]/.test(this)) {
return '"' + this.replace(/[&<"\/\\\x00-\x1f]/g, function (a) {
var c = escapes[a];
if (c) {
return c;
}
c = a.charCodeAt();
return '\\u00' +
Math.floor(c / 16).toString(16) +
(c % 16).toString(16);
}) + '"';
}
return '"' + this + '"';
};
function assume() {
if (!option.safe) {
if (option.rhino) {
predefined.union(rhino);
}
if (option.browser || option.sidebar) {
predefined.union(browser);
}
if (option.sidebar) {
predefined.union(sidebar);
}
if (option.widget) {
predefined.union(widget);
}
}
}
// Produce an error warning.
function quit(m, l, ch) {
throw {
name: 'JSLintError',
line: l,
character: ch,
message: m + " (" + Math.floor((l / lines.length) * 100) +
"% scanned)."
};
}
function warning(m, t, a, b, c, d) {
var ch, l, w;
t = t || nexttoken;
if (t.id === '(end)') {
t = token;
}
l = t.line || 0;
ch = t.from || 0;
w = {
id: '(error)',
raw: m,
evidence: lines[l] || '',
line: l,
character: ch,
a: a,
b: b,
c: c,
d: d
};
w.reason = m.supplant(w);
JSLINT.errors.push(w);
if (option.passfail) {
quit('Stopping. ', l, ch);
}
warnings += 1;
if (warnings === 50) {
quit("Too many errors.", l, ch);
}
return w;
}
function warningAt(m, l, ch, a, b, c, d) {
return warning(m, {
line: l,
from: ch
}, a, b, c, d);
}
function error(m, t, a, b, c, d) {
var w = warning(m, t, a, b, c, d);
quit("Stopping, unable to continue.", w.line, w.character);
}
function errorAt(m, l, ch, a, b, c, d) {
return error(m, {
line: l,
from: ch
}, a, b, c, d);
}
// lexical analysis
var lex = function () {
var character, from, line, s;
// Private lex methods
function nextLine() {
var at;
line += 1;
if (line >= lines.length) {
return false;
}
character = 0;
s = lines[line].replace(/\t/g, tab);
at = s.search(cx);
if (at >= 0) {
warningAt("Unsafe character.", line, at);
}
return true;
}
// Produce a token object. The token inherits from a syntax symbol.
function it(type, value) {
var i, t;
if (type === '(punctuator)' ||
(type === '(identifier)' && syntax.hasOwnProperty(value))) {
t = syntax[value];
// Mozilla bug workaround.
if (!t.id) {
t = syntax[type];
}
} else {
t = syntax[type];
}
t = Object.create(t);
if (type === '(string)') {
if (jx.test(value)) {
warningAt("Script URL.", line, from);
}
} else if (type === '(identifier)') {
if (option.nomen && (value.charAt(0) === '_' ||
value.charAt(value.length - 1) === '_')) {
warningAt("Unexpected '_' in '{a}'.", line, from, value);
}
}
t.value = value;
t.line = line;
t.character = character;
t.from = from;
i = t.id;
if (i !== '(endline)') {
prereg = i &&
(('(,=:[!&|?{};'.indexOf(i.charAt(i.length - 1)) >= 0) ||
i === 'return');
}
return t;
}
// Public lex methods
return {
init: function (source) {
if (typeof source === 'string') {
lines = source.
replace(/\r\n/g, '\n').
replace(/\r/g, '\n').
split('\n');
} else {
lines = source;
}
line = -1;
nextLine();
from = 0;
},
// token -- this is called by advance to get the next token.
token: function () {
var b, c, captures, d, depth, high, i, l, low, q, t;
function match(x) {
var r = x.exec(s), r1;
if (r) {
l = r[0].length;
r1 = r[1];
c = r1.charAt(0);
s = s.substr(l);
character += l;
from = character - r1.length;
return r1;
}
}
function string(x) {
var c, j, r = '';
if (jsonmode && x !== '"') {
warningAt("Strings must use doublequote.",
line, character);
}
if (xmode === x || xmode === 'string') {
if (xmode && xmode !== 'CDATA' && ax.test(x)) {
warning("ADsafe string violation.", line, character);
}
return it('(punctuator)', x);
}
function esc(n) {
var i = parseInt(s.substr(j + 1, n), 16);
j += n;
if (i >= 32 && i <= 127 &&
i !== 34 && i !== 92 && i !== 39) {
warningAt("Unnecessary escapement.", line, character);
}
character += n;
c = String.fromCharCode(i);
}
j = 0;
for (;;) {
while (j >= s.length) {
j = 0;
if (xmode !== 'xml' || !nextLine()) {
errorAt("Unclosed string.", line, from);
}
}
c = s.charAt(j);
if (c === x) {
character += 1;
s = s.substr(j + 1);
return it('(string)', r, x);
}
if (c < ' ') {
if (c === '\n' || c === '\r') {
break;
}
warningAt("Control character in string: {a}.",
line, character + j, s.slice(0, j));
} else if (c === '<') {
if (option.safe && xmode === 'xml') {
warningAt("ADsafe string violation.",
line, character + j);
} else if (s.charAt(j + 1) === '/' && ((xmode && xmode !== 'CDATA') || option.safe)) {
warningAt("Expected '<\\/' and instead saw '</'.", line, character);
} else if (s.charAt(j + 1) === '!' && ((xmode && xmode !== 'CDATA') || option.safe)) {
warningAt("Unexpected '<!' in a string.", line, character);
}
} else if (c === '\\') {
if (option.safe && xmode === 'xml') {
warningAt("ADsafe string violation.",
line, character + j);
}
j += 1;
character += 1;
c = s.charAt(j);
switch (c) {
case '\\':
case '\'':
case '"':
case '/':
break;
case 'b':
c = '\b';
break;
case 'f':
c = '\f';
break;
case 'n':
c = '\n';
break;
case 'r':
c = '\r';
break;
case 't':
c = '\t';
break;
case 'u':
esc(4);
break;
case 'v':
c = '\v';
break;
case 'x':
if (jsonmode) {
warningAt("Avoid \\x-.", line, character);
}
esc(2);
break;
default:
warningAt("Bad escapement.", line, character);
}
}
r += c;
character += 1;
j += 1;
}
}
for (;;) {
if (!s) {
return it(nextLine() ? '(endline)' : '(end)', '');
}
t = match(tx);
if (!t) {
t = '';
c = '';
while (s && s < '!') {
s = s.substr(1);
}
if (s) {
errorAt("Unexpected '{a}'.",
line, character, s.substr(0, 1));
}
}
// identifier
if (c.isAlpha() || c === '_' || c === '$') {
return it('(identifier)', t);
}
// number
if (c.isDigit()) {
if (!isFinite(Number(t))) {
warningAt("Bad number '{a}'.",
line, character, t);
}
if (s.substr(0, 1).isAlpha()) {
warningAt("Missing space after '{a}'.",
line, character, t);
}
if (c === '0') {
d = t.substr(1, 1);
if (d.isDigit()) {
if (token.id !== '.') {
warningAt("Don't use extra leading zeros '{a}'.",
line, character, t);
}
} else if (jsonmode && (d === 'x' || d === 'X')) {
warningAt("Avoid 0x-. '{a}'.",
line, character, t);
}
}
if (t.substr(t.length - 1) === '.') {
warningAt(
"A trailing decimal point can be confused with a dot '{a}'.",
line, character, t);
}
return it('(number)', t);
}
// string
switch (t) {
case '"':
case "'":
return string(t);
// // comment
case '//':
if (src || (xmode && !(xmode === 'script' || xmode === 'CDATA'))) {
warningAt("Unexpected comment.", line, character);
} else if (xmode === 'script' && /\<\/script\>/i.test(s)) {
warningAt("Unexpected <\/script> in comment.", line, character);
} else if ((option.safe || xmode === 'script') && ax.test(s)) {
warningAt("Dangerous comment.", line, character);
}
s = '';
token.comment = true;
break;
// /* comment
case '/*':
if (src || (xmode && !(xmode === 'script' || xmode === 'CDATA'))) {
warningAt("Unexpected comment.", line, character);
}
if (option.safe && ax.test(s)) {
warningAt("ADsafe comment violation.", line, character);
}
for (;;) {
i = s.search(lx);
if (i >= 0) {
break;
}
if (!nextLine()) {
errorAt("Unclosed comment.", line, character);
} else {
if (option.safe && ax.test(s)) {
warningAt("ADsafe comment violation.", line, character);
}
}
}
character += i + 2;
if (s.substr(i, 1) === '/') {
errorAt("Nested comment.", line, character);
}
s = s.substr(i + 2);
token.comment = true;
break;
// /*global /*extern /*members /*jslint */
case '/*global':
case '/*extern':
case '/*members':
case '/*member':
case '/*jslint':
case '*/':
return {
value: t,
type: 'special',
line: line,
character: character,
from: from
};
case '':
break;
// /
case '/':
if (prereg) {
depth = 0;
captures = 0;
l = 0;
for (;;) {
b = true;
c = s.charAt(l);
l += 1;
switch (c) {
case '':
errorAt("Unclosed regular expression.", line, from);
return;
case '/':
if (depth > 0) {
warningAt("Unescaped '{a}'.", line, from + l, '/');
}
c = s.substr(0, l - 1);
q = {
g: true,
i: true,
m: true
};
while (q[s.charAt(l)] === true) {
q[s.charAt(l)] = false;
l += 1;
}
character += l;
s = s.substr(l);
return it('(regex)', c);
case '\\':
c = s.charAt(0);
if (c < ' ') {
warningAt("Unexpected control character in regular expression.", line, from + l);
} else if (c === '<') {
warningAt("Unexpected escaped character '{a}' in regular expression.", line, from + l, c);
}
l += 1;
break;
case '(':
depth += 1;
b = false;
if (s.charAt(l) === '?') {
l += 1;
switch (s.charAt(l)) {
case ':':
case '=':
case '!':
l += 1;
break;
default:
warningAt("Expected '{a}' and instead saw '{b}'.", line, from + l, ':', s.charAt(l));
}
} else {
captures += 1;
}
break;
case ')':
if (depth === 0) {
warningAt("Unescaped '{a}'.", line, from + l, ')');
} else {
depth -= 1;
}
break;
case ' ':
q = 1;
while (s.charAt(l) === ' ') {
l += 1;
q += 1;
}
if (q > 1) {
warningAt("Spaces are hard to count. Use {{a}}.", line, from + l, q);
}
break;
case '[':
if (s.charAt(l) === '^') {
l += 1;
}
q = false;
klass: do {
c = s.charAt(l);
l += 1;
switch (c) {
case '[':
case '^':
warningAt("Unescaped '{a}'.", line, from + l, c);
q = true;
break;
case '-':
if (q) {
q = false;
} else {
warningAt("Unescaped '{a}'.", line, from + l, '-');
q = true;
}
break;
case ']':
if (!q) {
warningAt("Unescaped '{a}'.", line, from + l - 1, '-');
}
break klass;
case '\\':
c = s.charAt(0);
if (c < ' ') {
warningAt("Unexpected control character in regular expression.", line, from + l);
} else if (c === '<') {
warningAt("Unexpected escaped character '{a}' in regular expression.", line, from + l, c);
}
l += 1;
q = true;
break;
case '/':
warningAt("Unescaped '{a}'.", line, from + l - 1, '/');
q = true;
break;
case '<':
if (xmode === 'script') {
c = s.charAt(l);
if (c === '!' || c === '/') {
warningAt("HTML confusion in regular expression '<{a}'.", line, from + l, c);
}
}
q = true;
break;
default:
q = true;
}
} while (c);
break;
case '.':
if (option.regexp) {
warningAt("Unexpected '{a}'.", line, from + l, c);
}
break;
case ']':
case '?':
case '{':
case '}':
case '+':
case '*':
warningAt("Unescaped '{a}'.", line, from + l, c);
break;
case '<':
if (xmode === 'script') {
c = s.charAt(l);
if (c === '!' || c === '/') {
warningAt("HTML confusion in regular expression '<{a}'.", line, from + l, c);
}
}
}
if (b) {
switch (s.charAt(l)) {
case '?':
case '+':
case '*':
l += 1;
if (s.charAt(l) === '?') {
l += 1;
}
break;
case '{':
l += 1;
c = s.charAt(l);
if (c < '0' || c > '9') {
warningAt("Expected a number and instead saw '{a}'.", line, from + l, c);
}
l += 1;
low = +c;
for (;;) {
c = s.charAt(l);
if (c < '0' || c > '9') {
break;
}
l += 1;
low = +c + (low * 10);
}
high = low;
if (c === ',') {
l += 1;
high = Infinity;
c = s.charAt(l);
if (c >= '0' && c <= '9') {
l += 1;
high = +c;
for (;;) {
c = s.charAt(l);
if (c < '0' || c > '9') {
break;
}
l += 1;
high = +c + (high * 10);
}
}
}
if (s.charAt(l) !== '}') {
warningAt("Expected '{a}' and instead saw '{b}'.", line, from + l, '}', c);
} else {
l += 1;
}
if (s.charAt(l) === '?') {
l += 1;
}
if (low > high) {
warningAt("'{a}' should not be greater than '{b}'.", line, from + l, low, high);
}
}
}
}
c = s.substr(0, l - 1);
character += l;
s = s.substr(l);
return it('(regex)', c);
}
return it('(punctuator)', t);
// punctuator
default:
return it('(punctuator)', t);
}
}
},
// skip -- skip past the next occurrence of a particular string.
// If the argument is empty, skip to just before the next '<' character.
// This is used to ignore HTML content. Return false if it isn't found.
skip: function (p) {
var i, t = p;
if (nexttoken.id) {
if (!t) {
t = '';
if (nexttoken.id.substr(0, 1) === '<') {
lookahead.push(nexttoken);
return true;
}
} else if (nexttoken.id.indexOf(t) >= 0) {
return true;
}
}
token = nexttoken;
nexttoken = syntax['(end)'];
for (;;) {
i = s.indexOf(t || '<');
if (i >= 0) {
character += i + t.length;
s = s.substr(i + t.length);
return true;
}
if (!nextLine()) {
break;
}
}
return false;
}
};
}();
function addlabel(t, type) {
if (t === 'hasOwnProperty') {
error("'hasOwnProperty' is a really bad name.");
}
if (option.safe && funct['(global)']) {
warning('ADsafe global: ' + t + '.', token);
}
// Define t in the current function in the current scope.
if (funct.hasOwnProperty(t)) {
warning(funct[t] === true ?
"'{a}' was used before it was defined." :
"'{a}' is already defined.",
nexttoken, t);
}
funct[t] = type;
if (type === 'label') {
scope[t] = funct;
} else if (funct['(global)']) {
global[t] = funct;
if (implied.hasOwnProperty(t)) {
warning