Grunt insert string after pattern in file - node.js

I'm building a custom task for grunt that finds a particular font, and basically outputs a definition that uses a PHP variable for configuring that particular font.
It uses underscore and postcss.
It groups all CSS selectors that use that font, and outputs a string similar to this one:
selector1, selector2, selector3 {
font-family: <?php echo $font_1 ?>, Font 2, Font 3, Font 4;
}
Here is the code for the custom task:
// Extract configurable font data
// ======================================================================
grunt.registerTask('extractfontdata', 'Extract configurable properties', function () {
console.log('Extracting configurable font data');
var match = /Myriad Pro/gim;
var contents = grunt.file.read('assets/css/leadscon.css');
var css = postcss(function (css) {
var findings = {};
css.eachDecl(function (decl) {
if (decl.value.match( match ) && decl.parent.selector !== undefined) {
var fonts = decl.value.replace(/(\r\n|\n|\r|"|')/gm, "").split(',');
var prop = _.find(fonts, function(font) { return font.match(match) });
var finding = findings[ prop ] = findings[ prop ] || {};
finding.selectors = finding.selectors || [];
finding.fontstack = finding.fontstack || [];
finding.selectors.push( decl.parent.selector.replace(/(\r\n|\n|\r|"|'|\s)/gm, "").split(',') );
finding.fontstack.push( fonts );
finding.selectors = _(finding.selectors).chain().flatten().uniq().value();
finding.fontstack = _(finding.fontstack).chain().flatten().uniq().value();
}
});
var result = '';
var j = 0;
for ( var font in findings ) {
findings[font].fontstack.every(function(f, i) {
if (f.match(font)) {
findings[font].fontstack[i] = '<?php echo $font_' + j++ + ' ?>';
}
});
result += findings[font].selectors.join(',') + ' { font-family: ' + findings[font].fontstack.join(',') + ' } ';
}
console.log(result);
// Now insert result into header.php
}).process(contents);
});
This currently, will set result to:
body,.footer-widget.widget_nav_menu.widget-title
{
font-family: <?php echo $font_0 ?>, PT Sans, Helvetica Neue, Helvetica, Arial, sans-serif
}
h1,h2,h3,h4,h5,h6,.h1,.h2,.h3,.h4,.h5,.h6,.widget.widget-title,.widget_lc_cta,.header-widget.widget_lc_events.events,.widget_accordion_widget.accordion-widget.resp-tabs-container>.resp-accordion,article.single>.article-header.breadcrumbs,article.single>.article-header.meta
{
font-family: <?php echo $font_1 ?>, Open Sans Condensed, PT Sans, Helvetica Neue, Helvetica, Arial, sans-serif
}
I've added this code to header.php:
<style>
/* extractfontdata */
</style>
Now, how do I find the string "extractfontdata" in header.php, and insert result after it?

Well in case anyone is wondering, this worked for me:
// Now insert result into header.php
var header = grunt.file.read('header.php').split('\n');
var line_1 = _.indexOf(header, _(header).find(function(el) { return el.match(/extractfontdata/i) }) );
var line_2 = _.indexOf(header, _(header).find(function(el) { return el.match(/endextractfontdata/i) }));
var start = Math.min(line_1, line_2) + 1;
var end = Math.max(line_1, line_2);
var num = Math.min((end - start), 0);
header.splice(start, num, result);
for ( var i = start-2; i <= end+2; i++) {
console.log(header[i]);
}
grunt.file.write('header.php', header.join('\n'));

Related

How do you write SharePoint 2010 conditional formatting for this?

I am using SPD 2010 and SharePoint Sever 2010.
Using conditional formatting I'm trying to format a list so that if today's date is greater than 30 days before the start date column a cell will turn red.
I've tried several XPath expressions from other Stackoverflow entries but nothing has worked. I'm wondering if I am even adding the XPath expression in the right place: In SPD I am selecting a date from the desired column, choosing "Conditional Formatting", selecting "Format Column", selecting "Advanced" and putting my expressions in the XPath expression textbox.
Appreciate your help!
I'm going to suggest a non-Xpath approach, but if you're looking to stick with Xpath you should take a look at the answers on this similar question.
After struggling with this problem myself, I've taken to using JavaScript for conditional formatting, since it can work with dates (including the current date), numbers, and strings, and it can manipulate HTML pretty easily.
A bit of client side code can automatically:
Detect whether a list of conditional formatting rules exists
Create the list if necessary
Provide an interface for creating new rules (which are stored as list items) that should apply to the current page
Loop through all the current page's rules and apply them to any list view web parts detected on the same page
The nicest part of this approach is that I can add the web part to a page and just let the business users configure the formatting to their liking; no need for me to be further involved whenever they want to change something.
I put the combined HTML/CSS/JavaScript in a text file that can be saved to a document library somewhere in my site collection. To then add the conditional formatting to page, I just add a content editor web part to the page and set its "content link" property to be the path to the text file.
The content editor web part then displays a gray "Conditional Formatting" button that the user can click to view and modify the formatting rules, as seen in the screen shot below.
Here's the conditional formatting code for SharePoint 2010 that I use in my text file:
<div id="_conditional_formatting_link" style="display:none; ">
<div unselectable="on" style="display:inline-block; user-select:none; cursor:pointer; padding: 3px; background-color:#9b9b9b; color:white; border:1px solid #888;" onclick="javascript:var rules = document.getElementById('_conditional_formatting'); if(rules.style.display == 'none'){rules.style.display = 'inline-block'}else{rules.style.display = 'none'}">
Conditional Formatting
</div>
</div>
<div id="_conditional_formatting" style="display:none;background-color:#dfdfdf; border: 1px solid black; width:95%; max-width:1100px;">
<a style="border:0px;padding:5px;float:right;" title="Reapply Formatting" href="javascript:getConditions(false);">
<img style="border:0px;" src="/_layouts/images/staticrefresh.gif"/>
</a>
<ol id="_conditional_formatting_rules"></ol>
<div style="text-align:right; ">
<div id="_add_conditional_formatting_rule" unselectable="on" onclick="javascript: Add_Conditional_Formatting();" style="user-select:none; cursor:pointer; padding: 3px; margin: 3px; display:inline-block; background-color:#9b9b9b; border:1px solid #888; color:white;">Add Rule</div>
</div>
</div>
<script>
this.cfl = this.cfl ? this.cfl : new Object(null);
var conditionalFormattingList = "Conditional Formatting";
function getConditions(reloadRules) {
/* if reloadRules, query the conditions list and get all the rules. Otherwise just reapply the ones in memory to the current document. */
if (typeof reloadRules == "undefined") { reloadRules = true; }
if (reloadRules) {
var conditionalFormattingRules = document.getElementById("_conditional_formatting_rules");
while (conditionalFormattingRules.children.length > 0) { /* Clear out the currently displayed list of rules. */
conditionalFormattingRules.removeChild(conditionalFormattingRules.children[0]);
}
this.cfl.clientContext = new SP.ClientContext();
this.cfl.user = cfl.clientContext.get_web().get_currentUser();
var list = cfl.clientContext.get_web().get_lists().getByTitle(conditionalFormattingList);
var camlQuery = new SP.CamlQuery();
var folder = list.get_rootFolder();
camlQuery.set_viewXml('<View><Query><Where><Eq><FieldRef Name=\'URL\' /><Value Type=\'Text\'>' + document.location.pathname + '</Value></Eq></Where><OrderBy><FieldRef Name=\'Priority\' /><FieldRef Name=\'Name\' /></OrderBy></Query></View>');
this.cfl.items = list.getItems(camlQuery);
cfl.clientContext.load(cfl.user);
cfl.clientContext.load(list, 'EffectiveBasePermissions');
cfl.clientContext.load(cfl.items);
cfl.clientContext.load(folder);
}
this.cfl.clientContext.executeQueryAsync(
Function.createDelegate(this,
function () {
var Me = this.cfl.user.get_title();
if (reloadRules) {
var baseFormUrl = folder.get_serverRelativeUrl() + "/EditForm.aspx?ID=";
/* Figure out if the current user has access to create or edit items on the Conditional Formatting list */
var perms = list.get_effectiveBasePermissions();
this.cfl.hasEdit = perms.has(SP.PermissionKind.editListItems);
this.cfl.hasCreate = perms.has(SP.PermissionKind.addListItems);
/* Fill an array with our formatting rules */
this.cfl.targets = [];
var itemEnumerator = this.cfl.items.getEnumerator();
while (itemEnumerator.moveNext()) {
var item = itemEnumerator.get_current();
var targ = new Object(null);
targ.column = item.get_item("Column");
targ.comparison = item.get_item("Comparison");
targ.style = item.get_item("Style");
targ.scope = item.get_item("Scope");
targ.type = item.get_item("Type");
targ.value = item.get_item("Value"); if (targ.value == null) { targ.value = ""; }
targ.id = item.get_item("ID");
targ.offset = item.get_item("Offset");
cfl.targets.push(targ);
}
}
if (!this.cfl.hasCreate) { document.getElementById("_add_conditional_formatting_rule").style.display = "none"; }
for (var targetIterator = 0, len = cfl.targets.length; targetIterator < len; targetIterator++) {
var currentTarget = cfl.targets[targetIterator];
if (reloadRules) {
var rulelist = document.getElementById("_conditional_formatting_rules");
var ruletoadd = document.createElement("li");
var comparisondisplay = currentTarget.type.indexOf("Field") != -1 ? "value of the <b>" + currentTarget.value + "</b> column" : "<b>'" + currentTarget.value + "'</b>";
if (currentTarget.type == "Special" || currentTarget.type == "Number") {
if (currentTarget.value.toString().toLowerCase() == "[me]") { comparisondisplay = "<b>[Me](" + Me + ")</b>"; }
else { comparisondisplay = "<b>" + currentTarget.value + "</b>"; }
}
if (currentTarget.value == "") { comparisondisplay = "<b>(blank)</b>"; }
if (currentTarget.offset != null) {
comparisondisplay += "<b>" + (currentTarget.offset < 0 ? " " : " +") + currentTarget.offset + "</b>"
}
var editLink = this.cfl.hasEdit ? "<div style='display:inline-block;cursor:pointer;' onclick='SP.UI.ModalDialog.commonModalDialogOpen(" + '"' + baseFormUrl + currentTarget.id + '&Source=' + document.location.pathname + '"' + ",{},refreshPageConditions); '>" + "<img src='/_layouts/images/EDITITEM.GIF' style='vertical-align:middle;' title='Customize' alt='Customize'/>" + " </div>" : "";
ruletoadd.innerHTML = editLink + "When <b>" + currentTarget.column + "</b> "
+ currentTarget.comparison + " " + comparisondisplay
+ ", apply {" + (currentTarget.style == null ? "remove all formatting" : "<span style='" + currentTarget.style + "'>" + currentTarget.style + "</span>") + "} to the <b>" + currentTarget.scope + "</b>" + ((currentTarget.scope != "Cell" && currentTarget.scope != "Row") ? " column" : "");
rulelist.appendChild(ruletoadd);
}
var tables = document.querySelectorAll("table.ms-listviewtable"); /* Should get all the list view web parts on the page. */
var t_i = 0;
while (t_i < tables.length) {
var columnIndex = null; /* Index of the column to compare against */
var valueIndex = null; /* Index of a second column from which to pull the value to compare */
var styleTargetIndex = null; /* Index of a column to apply formatting to */
var thisTable = tables[t_i];
var headings = thisTable.rows[0].cells;
var h_i = 0;
while (h_i < headings.length) { /* Check all the column headings... */
var thisHeading = headings[h_i].querySelector("div:first-child");
if (thisHeading != null) {
/* In Internet Explorer, the headings have a DisplayName attribute you can grab. If that's not there, just grab the innerText or textContent */
var dispname = thisHeading.DisplayName ? thisHeading.DisplayName : (thisHeading.innerText ? thisHeading.innerText : thisHeading.textContent);
dispname = dispname.replace(/^\s+|\s+$/g, '');/* removes leading and trailing whitespace */
if (currentTarget.scope != "Cell" && currentTarget.scope != "Row") {
/*If the scope isn't Cell or Row, see if this is the cell to which the formatting should applied */
if (dispname == currentTarget.scope) { styleTargetIndex = h_i; }
}
if (currentTarget.type.indexOf("Field") != -1) {
/*If the value type is a Field, check to see if this is the field whose value we care about */
if (dispname == currentTarget.value.toString()) { valueIndex = h_i; }
}
if (dispname == currentTarget.column) { columnIndex = h_i; }
}
h_i += 1;
}
if (columnIndex != null) { /* If we found a matching heading, let's try to apply the rules... */
var rows = thisTable.rows;
for (var i = (rows.length > 0 ? 1 : 0) ; i < rows.length; i++) {
var cells = rows[i].children;
if (cells.length <= columnIndex) { continue }
var innerLink = cells[columnIndex].querySelector("a"); /* I want to specifically target links so that we can change their text color if necessary */
/* Populate valueToEval with the text value of the current cell, or its inner link if it has one */
var valueToEval = cells[columnIndex].innerText ? (innerLink != null ? innerLink.innerText : cells[columnIndex].innerText) : (innerLink != null ? innerLink.textContent : cells[columnIndex].textContent);
if (typeof (valueToEval) == "undefined") { valueToEval = "" } /* Treat empties as blanks */
var listValueToCompareAgainst = null;
if (valueIndex != null) { /* valueIndex only has a value if we need to grab the comparison value from another column on the list */
valueLink = cells[valueIndex].querySelector("a");
listValueToCompareAgainst = cells[valueIndex].innerText ? (valueLink != null ? valueLink.innerText : cells[valueIndex].innerText) : (valueLink != null ? valueLink.textContent : cells[valueIndex].textContent);
}
var needsStyling = false;
switch (currentTarget.type) {
case "Number":
if (!isNaN(Number(valueToEval))) {
valueToEval = +(valueToEval);
}
if (!isNaN(Number(currentTarget.value))) {
currentTarget.value = +(currentTarget.value);
}
break;
case "Date":
valueToEval = new Date(valueToEval);
currentTarget.value = new Date(currentTarget.value);
if (currentTarget.offset != null) {
currentTarget.value.setDate(currentTarget.value.getDate() + +(currentTarget.offset));
}
break;
case "Text": /* Already covered, bro */ break;
case "Date Field":
valueToEval = new Date(valueToEval);
currentTarget.value = new Date(listValueToCompareAgainst);
if (currentTarget.offset != null) {
currentTarget.value.setDate(currentTarget.value.getDate() + +(currentTarget.offset));
}
break;
case "Text Field": currentTarget.value = listValueToCompareAgainst; break;
case "Number Field":
if (!isNaN(Number(listValueToCompareAgainst))) {
currentTarget.value = listValueToCompareAgainst;
if (currentTarget.offset != null) {
currentTarget.value += Number(currentTarget.offset);
}
}
if (!isNaN(Number(valueToEval))) {
valueToEval = Number(valueToEval);
}
break;
case "Special":
if (currentTarget.value.toLowerCase) {
if (currentTarget.value.toLowerCase() == "[me]") { currentTarget.value = Me }
else if (currentTarget.value.toLowerCase().indexOf("[today]") != -1) {
var dateDifference = Number(currentTarget.value.toLowerCase().replace("[today]", "").replace(" ", "").replace("+", ""));
currentTarget.value = new Date();
if (!isNaN(dateDifference)) { currentTarget.value.setDate(currentTarget.value.getDate() + dateDifference); }
if (currentTarget.offset != null) {
currentTarget.value.setDate(currentTarget.value.getDate() + Number(currentTarget.offset));
}
valueToEval = new Date(valueToEval);
}
} else { valueToEval = new Date(valueToEval); }
break;
}
switch (currentTarget.comparison) {
case "Greater Than or Equal To": needsStyling = (valueToEval >= currentTarget.value); break;
case "Greater Than": needsStyling = (valueToEval > currentTarget.value); break;
case "Less Than or Equal To": needsStyling = (valueToEval <= currentTarget.value); break;
case "Less Than": needsStyling = (valueToEval < currentTarget.value); break;
case "Equal To": needsStyling = (valueToEval == currentTarget.value); break;
case "Not Equal To": needsStyling = (valueToEval != currentTarget.value); break;
case "Contains": needsStyling = (valueToEval.indexOf(currentTarget.value) != -1); break;
case "Does Not Contain": needsStyling = (valueToEval.indexOf(currentTarget.value) == -1); break;
}
if (needsStyling) {
var links;
if (currentTarget.scope != "Row") {
var targetIndex = (styleTargetIndex != null) ? styleTargetIndex : columnIndex;
cells[targetIndex].setAttribute("style", currentTarget.style);
links = cells[targetIndex].querySelectorAll("a");
} else {
rows[i].setAttribute("style", currentTarget.style);
for (var j = 0; j < cells.length; j++) {
cells[j].setAttribute("style", currentTarget.style);
}
links = rows[i].querySelectorAll("a");
}
for (var j = 0; j < links.length; j++) {
if (links[j].title != "Open Menu") {
links[j].setAttribute("style", currentTarget.style);
links[j].style.backgroundColor = "";
}
links[j].style.border = "0px";
}
}
}
}
t_i += 1;
}
}
document.getElementById("_conditional_formatting_link").style.display = "inline-block";
}
),
Function.createDelegate(this,
function (sender, args) { /* There was an error accessing the list. Time to create it! */
var lci = new SP.ListCreationInformation();
lci.set_title(conditionalFormattingList);
lci.set_templateType(SP.ListTemplateType.genericList);
var condition_list = clientContext.get_web().get_lists().add(lci);
clientContext.load(condition_list);
var colTitle = condition_list.get_fields().getByTitle("Title");
colTitle.set_required(false); colTitle.set_hidden(true); colTitle.update();
condition_list.update();
var colColumn = condition_list.get_fields().addFieldAsXml('<Field Description=\'The column to compare (must be visible on the page)\' DisplayName=\'Column\' Type=\'Text\'/>', true, SP.AddFieldOptions.defaultValue);
var colComparison = condition_list.get_fields().addFieldAsXml('<Field Description=\'\' Type=\'Choice\' DisplayName=\'Comparison\' Format=\'Dropdown\' FillInChoice=\'FALSE\'><Default>Equal To</Default><CHOICES><CHOICE>Greater Than</CHOICE><CHOICE>Greater Than or Equal To</CHOICE><CHOICE>Equal To</CHOICE><CHOICE>Less Than or Equal To</CHOICE><CHOICE>Less Than</CHOICE><CHOICE>Not Equal To</CHOICE><CHOICE>Contains</CHOICE><CHOICE>Does Not Contain</CHOICE></CHOICES></Field>', true, SP.AddFieldOptions.defaultValue);
var colValue = condition_list.get_fields().addFieldAsXml('<Field Description=\'The value or the name of a column to compare against\' DisplayName=\'Value\' Type=\'Text\'/>', true, SP.AddFieldOptions.defaultValue);
var colType = condition_list.get_fields().addFieldAsXml('<Field Description=\'Indicate the type of value you are comparing against. Choose Special if using the [Me] or [Today] placeholders.\' Type=\'Choice\' DisplayName=\'Type\' Format=\'Dropdown\' FillInChoice=\'FALSE\'><Default>Text</Default><CHOICES><CHOICE>Date</CHOICE><CHOICE>Number</CHOICE><CHOICE>Text</CHOICE><CHOICE>Date Field</CHOICE><CHOICE>Number Field</CHOICE><CHOICE>Text Field</CHOICE><CHOICE>Special</CHOICE></CHOICES></Field>');
var colOffset = condition_list.get_fields().addFieldAsXml('<Field Description=\'Optionally specify a number to offset the value by when comparing against a number or date.\' DisplayName=\'Offset\' Type=\'Number\' />', true, SP.AddFieldOptions.defaultValue);
var colStyle = condition_list.get_fields().addFieldAsXml('<Field NumLines=\'4\' Description=\'The CSS to apply to when the condition is met. Leave blank to remove formatting. Example syntax: background-color:darkred; color:white; font-weight:bold;\' DisplayName=\'Style\' Type=\'Note\' />', true, SP.AddFieldOptions.defaultValue);
var colScope = condition_list.get_fields().addFieldAsXml('<Field Description=\'The scope to which the style should be applied. Choose Row, Cell, or specify a column name.\' Type=\'Choice\' DisplayName=\'Scope\' Format=\'Dropdown\' FillInChoice=\'TRUE\'><Default>Cell</Default><CHOICES><CHOICE>Cell</CHOICE><CHOICE>Row</CHOICE></CHOICES></Field>', true, SP.AddFieldOptions.defaultValue);
var colPriority = condition_list.get_fields().addFieldAsXml('<Field Description=\'Priority determines which styles are applied in case of overlapping conditions. Higher numbers are applied later.\' DisplayName=\'Priority\' Type=\'Number\' />', true, SP.AddFieldOptions.defaultValue);
var colUrl = condition_list.get_fields().addFieldAsXml('<Field Description=\'Page where this rule should be applied\' DisplayName=\'URL\' Type=\'Text\'/>', true, SP.AddFieldOptions.defaultValue);
clientContext.executeQueryAsync(
Function.createDelegate(this, function () { getConditions(); }),
Function.createDelegate(this, function (sender, args) { document.getElementById("_conditional_formatting").innerHTML = ("An error occcurred while trying to apply conditional formatting to the list for you. Error details: " + args.get_message() + " " + args.get_stackTrace()); document.getElementById("_conditional_formatting_link").style.display = "inline-block"; }));
}
));
}
/* This method is called when the Add Rule button is clicked. */
function Add_Conditional_Formatting() {
/* Create a new item with only the URL and Priority fields filled out */
var currUrl = document.location.pathname;
var clientContext = new SP.ClientContext();
var itemCreateInfo = new SP.ListItemCreationInformation();
var newItem = clientContext.get_web().get_lists().getByTitle(conditionalFormattingList).addItem(itemCreateInfo);
newItem.set_item('URL', currUrl);
/* Give the new item a priority that will put it at the end of the list. This is kind of a hack since the highest priority is not necessarily the rulecount. */
newItem.set_item('Priority', document.getElementById("_conditional_formatting_rules").children.length + 1);
newItem.update();
clientContext.load(newItem);
clientContext.executeQueryAsync(Function.createDelegate(this, function () {
getConditions(); /* Reload to refresh the rules list after adding the item */
}), Function.createDelegate(this, function (sender, args) { alert(args.get_message()); }));
}
/* This method is called when the Edit Item dialog box is closed. It refreshes the page it the item was saved. */
function refreshPageConditions(result) { if (result != SP.UI.DialogResult.cancel) { window.location.replace(document.location.href) } }
ExecuteOrDelayUntilScriptLoaded(function () {
getConditions();
/* If there are any collapsible sections on the page, keep checking to see whether formatting needs to be reapplied */
this.cfl.TableRowCount = 0;
if (document.querySelector("img[alt='expand']") != null) {
setInterval(function () {
var tempTableRowCount = document.querySelectorAll("tr").length;
if (tempTableRowCount != this.cfl.TableRowCount) {
/* Only reapply formatting if the count of table rows is different than it was previously */
this.cfl.TableRowCount = tempTableRowCount;
getConditions(false) /* Passing false reapplies loaded rules without re-querying the SharePoint list */
}
}, 1000)
}
}, "SP.JS");
</script>

Outdated Browser - Only show banner from IE8 and lower. Currently IE9 is included

I want this code to only display outdated browser from IE8 and lower. Currently it also shows a message for IE9, which I want to exclude. I did try to remove the IE9 part of the code from the lowerthan part of the code, but no luck.
I got the code from: https://github.com/burocratik/outdated-browser
/*!--------------------------------------------------------------------
JAVASCRIPT "Outdated Browser"
Version: 1.1.0 - 2014
author: Burocratik
website: http://www.burocratik.com
* #preserve
-----------------------------------------------------------------------*/
var outdatedBrowser = function(options) {
//Variable definition (before ajax)
var outdated = document.getElementById("outdated");
// Default settings
this.defaultOpts = {
bgColor: '#f25648',
color: '#ffffff',
lowerThan: 'transform',
languagePath: '../outdatedbrowser/lang/en.html'
}
if (options) {
//assign css3 property to IE browser version
if(options.lowerThan == 'IE8' || options.lowerThan == 'borderSpacing') {
options.lowerThan = 'borderSpacing';
} else if (options.lowerThan == 'IE9' || options.lowerThan == 'boxShadow') {
options.lowerThan = 'boxShadow';
} else if (options.lowerThan == 'IE10' || options.lowerThan == 'transform' || options.lowerThan == '' || typeof options.lowerThan === "undefined") {
options.lowerThan = 'transform';
} else if (options.lowerThan == 'IE11' || options.lowerThan == 'borderImage') {
options.lowerThan = 'borderImage';
}
//all properties
this.defaultOpts.bgColor = options.bgColor;
this.defaultOpts.color = options.color;
this.defaultOpts.lowerThan = options.lowerThan;
this.defaultOpts.languagePath = options.languagePath;
bkgColor = this.defaultOpts.bgColor;
txtColor = this.defaultOpts.color;
cssProp = this.defaultOpts.lowerThan;
languagePath = this.defaultOpts.languagePath;
} else {
bkgColor = this.defaultOpts.bgColor;
txtColor = this.defaultOpts.color;
cssProp = this.defaultOpts.lowerThan;
languagePath = this.defaultOpts.languagePath;
};//end if options
//Define opacity and fadeIn/fadeOut functions
var done = true;
function function_opacity(opacity_value) {
outdated.style.opacity = opacity_value / 100;
outdated.style.filter = 'alpha(opacity=' + opacity_value + ')';
}
// function function_fade_out(opacity_value) {
// function_opacity(opacity_value);
// if (opacity_value == 1) {
// outdated.style.display = 'none';
// done = true;
// }
// }
function function_fade_in(opacity_value) {
function_opacity(opacity_value);
if (opacity_value == 1) {
outdated.style.display = 'block';
}
if (opacity_value == 100) {
done = true;
}
}
//check if element has a particular class
// function hasClass(element, cls) {
// return (' ' + element.className + ' ').indexOf(' ' + cls + ' ') > -1;
// }
var supports = (function() {
var div = document.createElement('div'),
vendors = 'Khtml Ms O Moz Webkit'.split(' '),
len = vendors.length;
return function(prop) {
if ( prop in div.style ) return true;
prop = prop.replace(/^[a-z]/, function(val) {
return val.toUpperCase();
});
while(len--) {
if ( vendors[len] + prop in div.style ) {
return true;
}
}
return false;
};
})();
//if browser does not supports css3 property (transform=default), if does > exit all this
if ( !supports(''+ cssProp +'') ) {
if (done && outdated.style.opacity !== '1') {
done = false;
for (var i = 1; i <= 100; i++) {
setTimeout((function (x) {
return function () {
function_fade_in(x);
};
})(i), i * 8);
}
}
}else{
return;
};//end if
//Check AJAX Options: if languagePath == '' > use no Ajax way, html is needed inside <div id="outdated">
if( languagePath === ' ' || languagePath.length == 0 ){
startStylesAndEvents();
}else{
grabFile(languagePath);
}
//events and colors
function startStylesAndEvents(){
var btnClose = document.getElementById("btnCloseUpdateBrowser");
var btnUpdate = document.getElementById("btnUpdateBrowser");
//check settings attributes
outdated.style.backgroundColor = bkgColor;
//way too hard to put !important on IE6
outdated.style.color = txtColor;
outdated.children[0].style.color = txtColor;
outdated.children[1].style.color = txtColor;
//check settings attributes
btnUpdate.style.color = txtColor;
// btnUpdate.style.borderColor = txtColor;
if (btnUpdate.style.borderColor) btnUpdate.style.borderColor = txtColor;
btnClose.style.color = txtColor;
//close button
btnClose.onmousedown = function() {
outdated.style.display = 'none';
return false;
};
//Override the update button color to match the background color
btnUpdate.onmouseover = function() {
this.style.color = bkgColor;
this.style.backgroundColor = txtColor;
};
btnUpdate.onmouseout = function() {
this.style.color = txtColor;
this.style.backgroundColor = bkgColor;
};
}//end styles and events
// IF AJAX with request ERROR > insert english default
var ajaxEnglishDefault = '<h6>Your browser is out-of-date!</h6>'
+ '<p>Update your browser to view this website correctly. <a id="btnUpdateBrowser" href="http://outdatedbrowser.com/">Update my browser now </a></p>'
+ '<p class="last">×</p>';
//** AJAX FUNCTIONS - Bulletproof Ajax by Jeremy Keith **
function getHTTPObject() {
var xhr = false;
if (window.XMLHttpRequest) {
xhr = new XMLHttpRequest();
} else if (window.ActiveXObject) {
try {
xhr = new ActiveXObject("Msxml2.XMLHTTP");
} catch(e) {
try {
xhr = new ActiveXObject("Microsoft.XMLHTTP");
} catch(e) {
xhr = false;
}
}
}
return xhr;
};//end function
function grabFile(file) {
var request = getHTTPObject();
if (request) {
request.onreadystatechange = function() {
displayResponse(request);
};
request.open("GET", file, true);
request.send(null);
}
return false;
};//end grabFile
function displayResponse(request) {
var insertContentHere = document.getElementById("outdated");
if (request.readyState == 4) {
if (request.status == 200 || request.status == 304) {
insertContentHere.innerHTML = request.responseText;
}else{
insertContentHere.innerHTML = ajaxEnglishDefault;
}
startStylesAndEvents();
}
return false;
};//end displayResponse
////////END of outdatedBrowser function
};
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8">
<title>Outdated Browser</title>
<meta name="description" content="A time saving tool for developers. It detects outdated browsers and advises users to upgrade to a new version.">
<!-- Styles -->
<link rel="stylesheet" href="../outdatedbrowser/outdatedbrowser.min.css">
<link href='http://fonts.googleapis.com/css?family=Open+Sans' rel='stylesheet' type='text/css'>
<style type="text/css">
body {
font-family: 'Open Sans', sans-serif; text-align: center;
background-color: #fafafa; color: #0a0a0a; line-height: 1.5em;
}
h1{font-size: 2.6em; line-height: 2em;}
h3, h4{line-height: 1em; margin: 2.5em 0 -.4em 0; text-transform: uppercase;}
h3 span, h4 span{text-transform: none;}
p{padding-bottom: 1em;}
p.designBy{position: absolute; bottom: 0; right: 1em; font-size: .8em;}
a {color: #0a0a0a;}
ul{list-style-type: none; padding: 0;}
</style>
</head>
<body>
<!-- ============= YOUR CONTENT ============= -->
<h1>Outdated Browser</h1>
<p>Remember: If you can't see the message, it's a good thing! You are using a modern browser :D</p>
<h3>DEFAULT properties but using jQuery (must support IE6+)</h3>
<p>bgColor: '#f25648', color: '#ffffff', lowerThan: 'transform' (<IE10), languagePath: 'your_path/outdatedbrowser/lang/en.html'</p>
<h3>What does it look like? <span>(it may differ in your tests) </span></h3>
<ul>
<li>IE7 - VISTA</li>
</ul>
<p class="designBy">by Bürocratik</p>
<!-- ============= Outdated Browser ============= -->
<div id="outdated"></div>
<!-- javascript includes -->
<script src="//ajax.googleapis.com/ajax/libs/jquery/1.8.0/jquery.min.js"></script>
<script src="../outdatedbrowser/outdatedbrowser.js"></script>
<!-- plugin call -->
<script>
//USING jQuery
$(document).ready(function() {
outdatedBrowser({
bgColor: '#f25648',
color: '#ffffff',
lowerThan: 'transform',
languagePath: '../outdatedbrowser/lang/en.html'
})
})
console.log(outdatedBrowser);
</script>
</script>
</body>
</html>

Given a polygon in latitude and longitude and a set of points, determine which points lie inside

Given a set of latlon points that make up a polygon, and a set of latlon points, how can I determine which points lie inside. The polygon may be up to 100km across and the error could be a few hundred meters (i.e. points inside or outside can fail or be included incorrectly at the edges). The polygons and points won't be near the poles. Can I treat the latlon points as 2d, or do I need to convert them to a projection of some kind? Circles are easy but I wonder if the error will be too great for a 100km wide polygon?
I plan to do this in C++ but the language doesn't matter.
Here is the (javascript) code from Openlayers to do it
/**
* Method: containsPoint
* Test if a point is inside a polygon. Points on a polygon edge are
* considered inside.
*
* Parameters:
* point - {<OpenLayers.Geometry.Point>}
*
* Returns:
* {Boolean | Number} The point is inside the polygon. Returns 1 if the
* point is on an edge. Returns boolean otherwise.
*/
containsPoint: function(point) {
var numRings = this.components.length;
var contained = false;
if(numRings > 0) {
// check exterior ring - 1 means on edge, boolean otherwise
contained = this.components[0].containsPoint(point);
if(contained !== 1) {
if(contained && numRings > 1) {
// check interior rings
var hole;
for(var i=1; i<numRings; ++i) {
hole = this.components[i].containsPoint(point);
if(hole) {
if(hole === 1) {
// on edge
contained = 1;
} else {
// in hole
contained = false;
}
break;
}
}
}
}
}
return contained;
}
Complete file can be found at Openlayers at Github
To get the idea behind this.components have a look at Collection.js
update:
In OpenLayers a polygon is a collection of linear rings. the containsPoint functon of this can be found at LinearRing.js
You can view actual demo here
<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
<title>How to Check If Point Exist in a Polygon - Google Maps API v3</title>
<script type="text/javascript" src="http://www.the-di-lab.com/polygon/jquery-1.4.2.min.js"></script>
<script type="text/javascript" src="https://maps.googleapis.com/maps/api/js?v=3.exp&sensor=false"></script>
<script type="text/javascript">
var map;
var boundaryPolygon;
function initialize() {
var mapProp = {
center: new google.maps.LatLng(26.038586842564317, 75.06787185438634),
zoom: 6,
mapTypeId: google.maps.MapTypeId.ROADMAP
};
map = new google.maps.Map(document.getElementById("map-canvas"), mapProp);
google.maps.Polygon.prototype.Contains = function (point) {
// ray casting alogrithm http://rosettacode.org/wiki/Ray-casting_algorithm
var crossings = 0,
path = this.getPath();
// for each edge
for (var i = 0; i < path.getLength() ; i++) {
var a = path.getAt(i),
j = i + 1;
if (j >= path.getLength()) {
j = 0;
}
var b = path.getAt(j);
if (rayCrossesSegment(point, a, b)) {
crossings++;
}
}
// odd number of crossings?
return (crossings % 2 == 1);
function rayCrossesSegment(point, a, b) {
var px = point.lng(),
py = point.lat(),
ax = a.lng(),
ay = a.lat(),
bx = b.lng(),
by = b.lat();
if (ay > by) {
ax = b.lng();
ay = b.lat();
bx = a.lng();
by = a.lat();
}
if (py == ay || py == by) py += 0.00000001;
if ((py > by || py < ay) || (px > Math.max(ax, bx))) return false;
if (px < Math.min(ax, bx)) return true;
var red = (ax != bx) ? ((by - ay) / (bx - ax)) : Infinity;
var blue = (ax != px) ? ((py - ay) / (px - ax)) : Infinity;
return (blue >= red);
}
};
google.maps.event.addListener(map, 'click', function (event) {
if (boundaryPolygon != null && boundaryPolygon.Contains(event.latLng)) {
alert("in")
document.getElementById("spnMsg").innerText = "This location is " + event.latLng + " inside the polygon.";
} else {
alert("out")
document.getElementById("spnMsg").innerText = "This location is " + event.latLng + " outside the polygon.";
}
});
}
function drawPolygon() {
initialize();
var boundary = '77.702866 28.987153, 77.699776 28.978594 ,77.735996 28.974164 ,77.719946 28.99346 ,77.713423 28.994361 ,77.711706 28.990382 ';
var boundarydata = new Array();
var latlongs = boundary.split(",");
for (var i = 0; i < latlongs.length; i++) {
latlong = latlongs[i].trim().split(" ");
boundarydata[i] = new google.maps.LatLng(latlong[1], latlong[0]);
}
boundaryPolygon = new google.maps.Polygon({
path: boundarydata,
strokeColor: "#0000FF",
strokeOpacity: 0.8,
strokeWeight: 2,
fillColor: 'Red',
fillOpacity: 0.4
});
google.maps.event.addListener(boundaryPolygon, 'click', function (event) {
document.getElementById("spnMsg").innerText = '';
if (boundaryPolygon.Contains(event.latLng)) {
document.getElementById("spnMsg").innerText = "This location is " + event.latLng + " inside the polygon.";
} else {
document.getElementById("spnMsg").innerText = "This location is " + event.latLng + " outside the polygon.";
}
});
map.setZoom(14);
map.setCenter(boundarydata[0]);
boundaryPolygon.setMap(map);
}
</script>
</head>
<body onload="initialize();drawPolygon();">
<form id="form1" runat="server">
<h3>Check If Point Exist in a Polygon</h3>
<h3>click on the polygon and out side the polygon for testing</h3>
<span id="spnMsg" style="font-family: Arial; text-align: center; font-size: 14px; color: red;">this is message</span>
<br />
<br />
<div id="map-canvas" style="width: auto; height: 500px;">
</div>
</form>
</body>
</html>
you can view more demos may be use full to you here
http://codeace.in/download/gmap/
you can download all the demo
by click on the file
"googlemap.zip" given in the index

Switch case not executing in javascript

I have created this script for redirection. It is working properly up to match case, but not executing the switch case. There is something wrong with code?
<script type="text/javascript">
window.onload = function () {
var elements = document.getElementsByTagName('a');
for (var i = 0; i < elements.length; i++) {
elements[i].href= escape(elements[i].href);
(function(index){
elements[index].onclick = function () {
var string = elements[index].href; //href value
var patt1=/\bwww.google.com/g;
var n=string.match(patt1);
switch (n) {
case "www.google.com":
var red = "http://yahoo.com";
elements[index].target = "_blank";
elements[index].href = red;
break;
default:
elements[index].href = unescape(string);
}
}
})(i);
}
}
</script>
www.google.com</br>
You can try this :
switch (true) {
case n == "www.google.com":
console.log(n);
var red = "http://yahoo.com";
elements[index].target = "_blank";
elements[index].href = red;
break;
default:
elements[index].href = unescape(string);
}

rotating text with fade-in

I currently have this code for displaying random customer testimonials.
I would like to replace the random function with a code that will display the quotes by their order and then repeat them.
<html style="direction:rtl;">
<DIV id=textrotator style="FONT: 16px arial ; text-align:right; WIDTH: 100%; COLOR: rgb(255,255,255)"></DIV>
<body bgcolor="#FFFFFF" alink="#FFFFFF" vlink="#FFFFFF" topmargin="0" leftmargin="0" rightmargin="0">
<script type = "text/javascript">
var hexinput = 255; // initial color value.
quotation = new Array()
quotation[0] = "text1"
quotation[1] = "text2"
quotation[2] = "text3"
function fadingtext()
{
if(hexinput >111)
{
hexinput -=11; // increase color value
document.getElementById("textrotator").style.color="rgb("+hexinput+","+hexinput+","+hexinput+")"; // Set color value.
setTimeout("fadingtext()",200); // 200ms per step
}
else
{
hexinput = 255; //reset hex value
}
}
function changetext()
{
if(!document.getElementById){return}
var which = Math.round(Math.random()*(quotation.length - 1));
document.getElementById("textrotator").innerHTML = quotation[which];
fadingtext();
setTimeout("changetext()",8000);
}
window.onload = changetext();
</script>
You need to make your index global. Throw which outside of the function and then just increment it, make sure to wrap when you get to the end.
This is the replacement for the "changetext" function:
var which = 0;
function changetext()
{
which += 1;
if (which >= quotation.length)
{
which = 0;
}
document.getElementById("textrotator").innerHTML = quotation[which];
fadingtext();
setTimeout("changetext()",8000);
}

Resources