I have a javascript file for history management. It is not supported by chrome when i am trying to navigate to back page with back button in the browser.I can see the url change but it doesnt go to preceeding page.
BrowserHistoryUtils = {
addEvent: function(elm, evType, fn, useCapture) {
useCapture = useCapture || false;
if (elm.addEventListener) {
elm.addEventListener(evType, fn, useCapture);
return true;
}
else if (elm.attachEvent) {
var r = elm.attachEvent('on' + evType, fn);
return r;
}
else {
elm['on' + evType] = fn;
}
}
}
BrowserHistory = (function() {
// type of browser
var browser = {
ie: false,
firefox: false,
safari: false,
opera: false,
version: -1
};
// if setDefaultURL has been called, our first clue
// that the SWF is ready and listening
//var swfReady = false;
// the URL we'll send to the SWF once it is ready
//var pendingURL = '';
// Default app state URL to use when no fragment ID present
var defaultHash = '';
// Last-known app state URL
var currentHref = document.location.href;
// Initial URL (used only by IE)
var initialHref = document.location.href;
// Initial URL (used only by IE)
var initialHash = document.location.hash;
// History frame source URL prefix (used only by IE)
var historyFrameSourcePrefix = 'history/historyFrame.html?';
// History maintenance (used only by Safari)
var currentHistoryLength = -1;
var historyHash = [];
var initialState = createState(initialHref, initialHref + '#' + initialHash, initialHash);
var backStack = [];
var forwardStack = [];
var currentObjectId = null;
//UserAgent detection
var useragent = navigator.userAgent.toLowerCase();
if (useragent.indexOf("opera") != -1) {
browser.opera = true;
} else if (useragent.indexOf("msie") != -1) {
browser.ie = true;
browser.version = parseFloat(useragent.substring(useragent.indexOf('msie') + 4));
} else if (useragent.indexOf("safari") != -1) {
browser.safari = true;
browser.version = parseFloat(useragent.substring(useragent.indexOf('safari') + 7));
} else if (useragent.indexOf("gecko") != -1) {
browser.firefox = true;
}
if (browser.ie == true && browser.version == 7) {
window["_ie_firstload"] = false;
}
// Accessor functions for obtaining specific elements of the page.
function getHistoryFrame()
{
return document.getElementById('ie_historyFrame');
}
function getAnchorElement()
{
return document.getElementById('firefox_anchorDiv');
}
function getFormElement()
{
return document.getElementById('safari_formDiv');
}
function getRememberElement()
{
return document.getElementById("safari_remember_field");
}
// Get the Flash player object for performing ExternalInterface callbacks.
// Updated for changes to SWFObject2.
function getPlayer(id) {
if (id && document.getElementById(id)) {
var r = document.getElementById(id);
if (typeof r.SetVariable != "undefined") {
return r;
}
else {
var o = r.getElementsByTagName("object");
var e = r.getElementsByTagName("embed");
if (o.length > 0 && typeof o[0].SetVariable != "undefined") {
return o[0];
}
else if (e.length > 0 && typeof e[0].SetVariable != "undefined") {
return e[0];
}
}
}
else {
var o = document.getElementsByTagName("object");
var e = document.getElementsByTagName("embed");
if (e.length > 0 && typeof e[0].SetVariable != "undefined") {
return e[0];
}
else if (o.length > 0 && typeof o[0].SetVariable != "undefined") {
return o[0];
}
else if (o.length > 1 && typeof o[1].SetVariable != "undefined") {
return o[1];
}
}
return undefined;
}
function getPlayers() {
var players = [];
if (players.length == 0) {
var tmp = document.getElementsByTagName('object');
players = tmp;
}
if (players.length == 0 || players[0].object == null) {
var tmp = document.getElementsByTagName('embed');
players = tmp;
}
return players;
}
function getIframeHash() {
var doc = getHistoryFrame().contentWindow.document;
var hash = String(doc.location.search);
if (hash.length == 1 && hash.charAt(0) == "?") {
hash = "";
}
else if (hash.length >= 2 && hash.charAt(0) == "?") {
hash = hash.substring(1);
}
return hash;
}
/* Get the current location hash excluding the '#' symbol. */
function getHash() {
// It would be nice if we could use document.location.hash here,
// but it's faulty sometimes.
var idx = document.location.href.indexOf('#');
return (idx >= 0) ? document.location.href.substr(idx+1) : '';
}
/* Get the current location hash excluding the '#' symbol. */
function setHash(hash) {
// It would be nice if we could use document.location.hash here,
// but it's faulty sometimes.
if (hash == '') hash = '#'
document.location.hash = hash;
}
function createState(baseUrl, newUrl, flexAppUrl) {
return { 'baseUrl': baseUrl, 'newUrl': newUrl, 'flexAppUrl': flexAppUrl, 'title': null };
}
/* Add a history entry to the browser.
* baseUrl: the portion of the location prior to the '#'
* newUrl: the entire new URL, including '#' and following fragment
* flexAppUrl: the portion of the location following the '#' only
*/
function addHistoryEntry(baseUrl, newUrl, flexAppUrl) {
//delete all the history entries
forwardStack = [];
if (browser.ie) {
//Check to see if we are being asked to do a navigate for the first
//history entry, and if so ignore, because it's coming from the creation
//of the history iframe
if (flexAppUrl == defaultHash && document.location.href == initialHref && window['_ie_firstload']) {
currentHref = initialHref;
return;
}
if ((!flexAppUrl || flexAppUrl == defaultHash) && window['_ie_firstload']) {
newUrl = baseUrl + '#' + defaultHash;
flexAppUrl = defaultHash;
} else {
// for IE, tell the history frame to go somewhere without a '#'
// in order to get this entry into the browser history.
getHistoryFrame().src = historyFrameSourcePrefix + flexAppUrl;
}
setHash(flexAppUrl);
} else {
//ADR
if (backStack.length == 0 && initialState.flexAppUrl == flexAppUrl) {
initialState = createState(baseUrl, newUrl, flexAppUrl);
} else if(backStack.length > 0 && backStack[backStack.length - 1].flexAppUrl == flexAppUrl) {
backStack[backStack.length - 1] = createState(baseUrl, newUrl, flexAppUrl);
}
if (browser.safari) {
// for Safari, submit a form whose action points to the desired URL
if (browser.version <= 419.3) {
var file = window.location.pathname.toString();
file = file.substring(file.lastIndexOf("/")+1);
getFormElement().innerHTML = '<form name="historyForm" action="'+file+'#' + flexAppUrl + '" method="GET"></form>';
//get the current elements and add them to the form
var qs = window.location.search.substring(1);
var qs_arr = qs.split("&");
for (var i = 0; i < qs_arr.length; i++) {
var tmp = qs_arr[i].split("=");
var elem = document.createElement("input");
elem.type = "hidden";
elem.name = tmp[0];
elem.value = tmp[1];
document.forms.historyForm.appendChild(elem);
}
document.forms.historyForm.submit();
} else {
top.location.hash = flexAppUrl;
}
// We also have to maintain the history by hand for Safari
historyHash[history.length] = flexAppUrl;
_storeStates();
} else {
// Otherwise, write an anchor into the page and tell the browser to go there
addAnchor(flexAppUrl);
setHash(flexAppUrl);
}
}
backStack.push(createState(baseUrl, newUrl, flexAppUrl));
}
function _storeStates() {
if (browser.safari) {
getRememberElement().value = historyHash.join(",");
}
}
function handleBackButton() {
//The "current" page is always at the top of the history stack.
var current = backStack.pop();
if (!current) { return; }
var last = backStack[backStack.length - 1];
if (!last && backStack.length == 0){
last = initialState;
}
forwardStack.push(current);
}
function handleForwardButton() {
//summary: private method. Do not call this directly.
var last = forwardStack.pop();
if (!last) { return; }
backStack.push(last);
}
function handleArbitraryUrl() {
//delete all the history entries
forwardStack = [];
}
/* Called periodically to poll to see if we need to detect navigation that has occurred */
function checkForUrlChange() {
if (browser.ie) {
if (currentHref != document.location.href && currentHref + '#' != document.location.href) {
//This occurs when the user has navigated to a specific URL
//within the app, and didn't use browser back/forward
//IE seems to have a bug where it stops updating the URL it
//shows the end-user at this point, but programatically it
//appears to be correct. Do a full app reload to get around
//this issue.
if (browser.version < 7) {
currentHref = document.location.href;
document.location.reload();
} else {
if (getHash() != getIframeHash()) {
// this.iframe.src = this.blankURL + hash;
var sourceToSet = historyFrameSourcePrefix + getHash();
getHistoryFrame().src = sourceToSet;
}
}
}
}
if (browser.safari) {
// For Safari, we have to check to see if history.length changed.
if (currentHistoryLength >= 0 && history.length != currentHistoryLength) {
//alert("did change: " + history.length + ", " + historyHash.length + "|" + historyHash[history.length] + "|>" + historyHash.join("|"));
// If it did change, then we have to look the old state up
// in our hand-maintained array since document.location.hash
// won't have changed, then call back into BrowserManager.
currentHistoryLength = history.length;
var flexAppUrl = historyHash[currentHistoryLength];
if (flexAppUrl == '') {
//flexAppUrl = defaultHash;
}
//ADR: to fix multiple
if (typeof BrowserHistory_multiple != "undefined" && BrowserHistory_multiple == true) {
var pl = getPlayers();
for (var i = 0; i < pl.length; i++) {
pl[i].browserURLChange(flexAppUrl);
}
} else {
getPlayer().browserURLChange(flexAppUrl);
}
_storeStates();
}
}
if (browser.firefox) {
if (currentHref != document.location.href) {
var bsl = backStack.length;
var urlActions = {
back: false,
forward: false,
set: false
}
if ((window.location.hash == initialHash || window.location.href == initialHref) && (bsl == 1)) {
urlActions.back = true;
// FIXME: could this ever be a forward button?
// we can't clear it because we still need to check for forwards. Ugg.
// clearInterval(this.locationTimer);
handleBackButton();
}
// first check to see if we could have gone forward. We always halt on
// a no-hash item.
if (forwardStack.length > 0) {
if (forwardStack[forwardStack.length-1].flexAppUrl == getHash()) {
urlActions.forward = true;
handleForwardButton();
}
}
// ok, that didn't work, try someplace back in the history stack
if ((bsl >= 2) && (backStack[bsl - 2])) {
if (backStack[bsl - 2].flexAppUrl == getHash()) {
urlActions.back = true;
handleBackButton();
}
}
if (!urlActions.back && !urlActions.forward) {
var foundInStacks = {
back: -1,
forward: -1
}
for (var i = 0; i < backStack.length; i++) {
if (backStack[i].flexAppUrl == getHash() && i != (bsl - 2)) {
arbitraryUrl = true;
foundInStacks.back = i;
}
}
for (var i = 0; i < forwardStack.length; i++) {
if (forwardStack[i].flexAppUrl == getHash() && i != (bsl - 2)) {
arbitraryUrl = true;
foundInStacks.forward = i;
}
}
handleArbitraryUrl();
}
// Firefox changed; do a callback into BrowserManager to tell it.
currentHref = document.location.href;
var flexAppUrl = getHash();
if (flexAppUrl == '') {
//flexAppUrl = defaultHash;
}
//ADR: to fix multiple
if (typeof BrowserHistory_multiple != "undefined" && BrowserHistory_multiple == true) {
var pl = getPlayers();
for (var i = 0; i < pl.length; i++) {
pl[i].browserURLChange(flexAppUrl);
}
} else {
getPlayer().browserURLChange(flexAppUrl);
}
}
}
//setTimeout(checkForUrlChange, 50);
}
/* Write an anchor into the page to legitimize it as a URL for Firefox et al. */
function addAnchor(flexAppUrl)
{
if (document.getElementsByName(flexAppUrl).length == 0) {
getAnchorElement().innerHTML += "<a name='" + flexAppUrl + "'>" + flexAppUrl + "</a>";
}
}
var _initialize = function () {
if (browser.ie)
{
var scripts = document.getElementsByTagName('script');
for (var i = 0, s; s = scripts[i]; i++) {
if (s.src.indexOf("history.js") > -1) {
var iframe_location = (new String(s.src)).replace("history.js", "historyFrame.html");
}
}
historyFrameSourcePrefix = iframe_location + "?";
var src = historyFrameSourcePrefix;
var iframe = document.createElement("iframe");
iframe.id = 'ie_historyFrame';
iframe.name = 'ie_historyFrame';
//iframe.src = historyFrameSourcePrefix;
try {
document.body.appendChild(iframe);
} catch(e) {
setTimeout(function() {
document.body.appendChild(iframe);
}, 0);
}
}
if (browser.safari)
{
var rememberDiv = document.createElement("div");
rememberDiv.id = 'safari_rememberDiv';
document.body.appendChild(rememberDiv);
rememberDiv.innerHTML = '<input type="text" id="safari_remember_field" style="width: 500px;">';
var formDiv = document.createElement("div");
formDiv.id = 'safari_formDiv';
document.body.appendChild(formDiv);
var reloader_content = document.createElement('div');
reloader_content.id = 'safarireloader';
var scripts = document.getElementsByTagName('script');
for (var i = 0, s; s = scripts[i]; i++) {
if (s.src.indexOf("history.js") > -1) {
html = (new String(s.src)).replace(".js", ".html");
}
}
reloader_content.innerHTML = '<iframe id="safarireloader-iframe" src="about:blank" frameborder="no" scrolling="no"></iframe>';
document.body.appendChild(reloader_content);
reloader_content.style.position = 'absolute';
reloader_content.style.left = reloader_content.style.top = '-9999px';
iframe = reloader_content.getElementsByTagName('iframe')[0];
if (document.getElementById("safari_remember_field").value != "" ) {
historyHash = document.getElementById("safari_remember_field").value.split(",");
}
}
if (browser.firefox)
{
var anchorDiv = document.createElement("div");
anchorDiv.id = 'firefox_anchorDiv';
document.body.appendChild(anchorDiv);
}
//setTimeout(checkForUrlChange, 50);
}
return {
historyHash: historyHash,
backStack: function() { return backStack; },
forwardStack: function() { return forwardStack },
getPlayer: getPlayer,
initialize: function(src) {
_initialize(src);
},
setURL: function(url) {
document.location.href = url;
},
getURL: function() {
return document.location.href;
},
getTitle: function() {
return document.title;
},
setTitle: function(title) {
try {
backStack[backStack.length - 1].title = title;
} catch(e) { }
//if on safari, set the title to be the empty string.
if (browser.safari) {
if (title == "") {
try {
var tmp = window.location.href.toString();
title = tmp.substring((tmp.lastIndexOf("/")+1), tmp.lastIndexOf("#"));
} catch(e) {
title = "";
}
}
}
document.title = title;
},
setDefaultURL: function(def)
{
defaultHash = def;
def = getHash();
//trailing ? is important else an extra frame gets added to the history
//when navigating back to the first page. Alternatively could check
//in history frame navigation to compare # and ?.
if (browser.ie)
{
window['_ie_firstload'] = true;
var sourceToSet = historyFrameSourcePrefix + def;
var func = function() {
getHistoryFrame().src = sourceToSet;
window.location.replace("#" + def);
setInterval(checkForUrlChange, 50);
}
try {
func();
} catch(e) {
window.setTimeout(function() { func(); }, 0);
}
}
if (browser.safari)
{
currentHistoryLength = history.length;
if (historyHash.length == 0) {
historyHash[currentHistoryLength] = def;
var newloc = "#" + def;
window.location.replace(newloc);
} else {
//alert(historyHash[historyHash.length-1]);
}
//setHash(def);
setInterval(checkForUrlChange, 50);
}
if (browser.firefox || browser.opera)
{
var reg = new RegExp("#" + def + "$");
if (window.location.toString().match(reg)) {
} else {
var newloc ="#" + def;
window.location.replace(newloc);
}
setInterval(checkForUrlChange, 50);
//setHash(def);
}
},
/* Set the current browser URL; called from inside BrowserManager to propagate
* the application state out to the container.
*/
setBrowserURL: function(flexAppUrl, objectId) {
if (browser.ie && typeof objectId != "undefined") {
currentObjectId = objectId;
}
//fromIframe = fromIframe || false;
//fromFlex = fromFlex || false;
//alert("setBrowserURL: " + flexAppUrl);
//flexAppUrl = (flexAppUrl == "") ? defaultHash : flexAppUrl ;
var pos = document.location.href.indexOf('#');
var baseUrl = pos != -1 ? document.location.href.substr(0, pos) : document.location.href;
var newUrl = baseUrl + '#' + flexAppUrl;
if (document.location.href != newUrl && document.location.href + '#' != newUrl) {
currentHref = newUrl;
addHistoryEntry(baseUrl, newUrl, flexAppUrl);
currentHistoryLength = history.length;
}
return false;
},
browserURLChange: function(flexAppUrl) {
var objectId = null;
if (browser.ie && currentObjectId != null) {
objectId = currentObjectId;
}
pendingURL = '';
if (typeof BrowserHistory_multiple != "undefined" && BrowserHistory_multiple == true) {
var pl = getPlayers();
for (var i = 0; i < pl.length; i++) {
try {
pl[i].browserURLChange(flexAppUrl);
} catch(e) { }
}
} else {
try {
getPlayer(objectId).browserURLChange(flexAppUrl);
} catch(e) { }
}
currentObjectId = null;
}
}
})();
// Initialization
// Automated unit testing and other diagnostics
function setURL(url)
{
document.location.href = url;
}
function backButton()
{
history.back();
}
function forwardButton()
{
history.forward();
}
function goForwardOrBackInHistory(step)
{
history.go(step);
}
//BrowserHistoryUtils.addEvent(window, "load", function() { BrowserHistory.initialize(); });
(function(i) {
var u =navigator.userAgent;var e=/*#cc_on!#*/false;
var st = setTimeout;
if(/webkit/i.test(u)){
st(function(){
var dr=document.readyState;
if(dr=="loaded"||dr=="complete"){i()}
else{st(arguments.callee,10);}},10);
} else if((/mozilla/i.test(u)&&!/(compati)/.test(u)) || (/opera/i.test(u))){
document.addEventListener("DOMContentLoaded",i,false);
} else if(e){
(function(){
var t=document.createElement('doc:rdy');
try{t.doScroll('left');
i();t=null;
}catch(e){st(arguments.callee,0);}})();
} else{
window.onload=i;
}
})( function() {BrowserHistory.initialize();} );
The script doesn't support chrome. Read through it in most of the functions like checkForUrlChange() it looks at the name of the browser to decide what to do.
Because chrome and safari are both based on webkit, you can try to change the line useragent.indexOf("safari") != -1 to useragent.indexOf("safari") != -1 || useragent.indexOf("chrome") != -1 to see if that works.
If not, try using unfocus history keeper. It supports Chrome.
(http://www.unfocus.com/projects/historykeeper/)
Related
I upgrade magento from 1.8.1 to 1.9.0, and I have a problem with one js file:
TypeError: $(...) is null
$('product_addtocart_form').getElements().each(function(el) {
simple_product_pricing.js (line 1131, col 5)
I think this file is related to the Ayasoftware_SimpleProductPricing, maybe someone can help me to solve this. Before upgrade in 1.8.1 version everything was fine, in 1.9.0 version I have this error.
I will add here the entire js:
/*
Some of these override earlier varien/product.js methods, therefore
varien/product.js must have been included prior to this file.
some of these functions were initially written by Matt Dean ( http://organicinternet.co.uk/ )
*/
Product.Config.prototype.getMatchingSimpleProduct = function(){
var inScopeProductIds = this.getInScopeProductIds();
if ((typeof inScopeProductIds != 'undefined') && (inScopeProductIds.length == 1)) {
return inScopeProductIds[0];
}
return false;
};
/*
Find products which are within consideration based on user's selection of
config options so far
Returns a normal array containing product ids
allowedProducts is a normal numeric array containing product ids.
childProducts is a hash keyed on product id
optionalAllowedProducts lets you pass a set of products to restrict by,
in addition to just using the ones already selected by the user
*/
Product.Config.prototype.getInScopeProductIds = function(optionalAllowedProducts) {
var childProducts = this.config.childProducts;
var allowedProducts = [];
if ((typeof optionalAllowedProducts != 'undefined') && (optionalAllowedProducts.length > 0)) {
allowedProducts = optionalAllowedProducts;
}
for(var s=0, len=this.settings.length-1; s<=len; s++) {
if (this.settings[s].selectedIndex <= 0){
break;
}
var selected = this.settings[s].options[this.settings[s].selectedIndex];
if (s==0 && allowedProducts.length == 0){
allowedProducts = selected.config.allowedProducts;
} else {
allowedProducts = allowedProducts.intersect(selected.config.allowedProducts).uniq();
}
}
//If we can't find any products (because nothing's been selected most likely)
//then just use all product ids.
if ((typeof allowedProducts == 'undefined') || (allowedProducts.length == 0)) {
productIds = Object.keys(childProducts);
} else {
productIds = allowedProducts;
}
return productIds;
};
Product.Config.prototype.getProductIdOfCheapestProductInScope = function(priceType, optionalAllowedProducts) {
var childProducts = this.config.childProducts;
var productIds = this.getInScopeProductIds(optionalAllowedProducts);
var minPrice = Infinity;
var lowestPricedProdId = false;
//Get lowest price from product ids.
for (var x=0, len=productIds.length; x<len; ++x) {
var thisPrice = Number(childProducts[productIds[x]][priceType]);
if (thisPrice < minPrice) {
minPrice = thisPrice;
lowestPricedProdId = productIds[x];
}
}
return lowestPricedProdId;
};
Product.Config.prototype.getProductIdOfMostExpensiveProductInScope = function(priceType, optionalAllowedProducts) {
var childProducts = this.config.childProducts;
var productIds = this.getInScopeProductIds(optionalAllowedProducts);
var maxPrice = 0;
var highestPricedProdId = false;
//Get highest price from product ids.
for (var x=0, len=productIds.length; x<len; ++x) {
var thisPrice = Number(childProducts[productIds[x]][priceType]);
if (thisPrice >= maxPrice) {
maxPrice = thisPrice;
highestPricedProdId = productIds[x];
}
}
return highestPricedProdId;
};
Product.OptionsPrice.prototype.updateSpecialPriceDisplay = function(price, finalPrice) {
var prodForm = $('product_addtocart_form');
jQuery('p.msg').hide();
jQuery('div.price-box').show();
var specialPriceBox = prodForm.select('p.special-price');
var oldPricePriceBox = prodForm.select('p.old-price, p.was-old-price');
var magentopriceLabel = prodForm.select('span.price-label');
if (price == finalPrice) {
//specialPriceBox.each(function(x) {x.hide();});
magentopriceLabel.each(function(x) {x.hide();});
oldPricePriceBox.each(function(x) { x.hide();
// x.removeClassName('old-price');
// x.addClassName('was-old-price');
});
jQuery('.product-shop').removeClass('sale-product') ;
}else{
specialPriceBox.each(function(x) {x.show();});
magentopriceLabel.each(function(x) {x.show();});
oldPricePriceBox.each(function(x) { x.show();
x.removeClassName('was-old-price');
x.addClassName('old-price');
});
jQuery('.product-shop').addClass('sale-product') ;
}
};
//This triggers reload of price and other elements that can change
//once all options are selected
Product.Config.prototype.reloadPrice = function() {
var childProductId = this.getMatchingSimpleProduct();
var childProducts = this.config.childProducts;
var usingZoomer = false;
if(this.config.imageZoomer){
usingZoomer = true;
}
if(childProductId){
var price = childProducts[childProductId]["price"];
var finalPrice = childProducts[childProductId]["finalPrice"];
optionsPrice.productPrice = finalPrice;
optionsPrice.productOldPrice = price;
optionsPrice.reload();
optionsPrice.reloadPriceLabels(true);
optionsPrice.updateSpecialPriceDisplay(price, finalPrice);
if(this.config.updateShortDescription) {
this.updateProductShortDescription(childProductId);
}
if(this.config.updateDescription) {
this.updateProductDescription(childProductId);
}
if(this.config.updateProductName) {
this.updateProductName(childProductId);
}
if(this.config.customStockDisplay) {
this.updateProductAvailability(childProductId);
}
this.showTierPricingBlock(childProductId, this.config.productId);
if (usingZoomer) {
this.showFullImageDiv(childProductId, this.config.productId);
} else {
if(this.config.updateproductimage) {
this.updateProductImage(childProductId);
}
}
} else {
var cheapestPid = this.getProductIdOfCheapestProductInScope("finalPrice");
var price = childProducts[cheapestPid]["price"];
var finalPrice = childProducts[cheapestPid]["finalPrice"];
optionsPrice.productPrice = finalPrice;
optionsPrice.productOldPrice = price;
optionsPrice.reload();
optionsPrice.reloadPriceLabels(false);
if(this.config.updateProductName) {
this.updateProductName(false);
}
if(this.config.updateShortDescription) {
this.updateProductShortDescription(false);
}
if(this.config.updateDescription) {
this.updateProductDescription(false);
}
if(this.config.customStockDisplay) {
this.updateProductAvailability(false);
}
optionsPrice.updateSpecialPriceDisplay(price, finalPrice);
this.showTierPricingBlock(false);
this.showCustomOptionsBlock(false, false);
if (usingZoomer) {
this.showFullImageDiv(false, false);
} else {
if(this.config.updateproductimage) {
this.updateProductImage(false);
}
}
}
};
Product.Config.prototype.updateProductImage = function(productId) {
var imageUrl = this.config.imageUrl;
if(productId && this.config.childProducts[productId].imageUrl) {
imageUrl = this.config.childProducts[productId].imageUrl;
}
if (!imageUrl) {
return;
}
if($('image')) {
$('image').src = imageUrl;
} else {
$$('#product_addtocart_form p.product-image img').each(function(el) {
var dims = el.getDimensions();
el.src = imageUrl;
el.width = dims.width;
el.height = dims.height;
});
}
};
Product.Config.prototype.updateProductName = function(productId) {
var productName = this.config.productName;
if (productId && this.config.ProductNames[productId].ProductName) {
productName = this.config.ProductNames[productId].ProductName;
}
$$('#product_addtocart_form div.product-name h1').each(function(el) {
el.innerHTML = productName;
});
var productSku = this.config.sku ;
if (productId && this.config.childProducts[productId].sku) {
productSku = this.config.childProducts[productId].sku ;
}
jQuery('.sku span').text(productSku) ;
var productDelivery = this.config.delivery;
if (productId && this.config.childProducts[productId].delivery) {
productDelivery = this.config.childProducts[productId].delivery ;
}
jQuery('.delivery-info').html(productDelivery) ;
var productReturns = this.config.returns;
if (productId && this.config.childProducts[productId].returns) {
productReturns = this.config.childProducts[productId].returns ;
}
jQuery('.returns-info').html(productReturns) ;
var productDownloads = this.config.downloads;
if (productId && this.config.childProducts[productId].downloads) {
productDownloads = this.config.childProducts[productId].downloads;
}
if (productDownloads) jQuery('.downloads-info').html(productDownloads) ;
else jQuery('.downloads-info').html('There are no downloads for this product') ;
var productAttribs = this.config.attributesTable;
if (productId && this.config.childProducts[productId].attributesTable) {
productAttribs = this.config.childProducts[productId].attributesTable ;
}
jQuery('.attribs-info').html(productAttribs) ;
decorateTable('product-attribute-specs-table') ;
if (productId && this.config.childProducts[productId].isNew) {
jQuery('.product-image .new-label').show() ;
} else {
jQuery('.product-image .new-label').hide() ;
}
if (productId && this.config.childProducts[productId].isOnSale) {
jQuery('.product-image .sale-label').show() ;
} else {
jQuery('.product-image .sale-label').hide() ;
}
if (productId) jQuery('input[name="pid"]').val(productId) ;
};
Product.Config.prototype.updateProductAvailability = function(productId) {
var stockInfo = this.config.stockInfo;
var is_in_stock = false;
var stockLabel = '';
if (productId && stockInfo[productId]["stockLabel"]) {
stockLabel = stockInfo[productId]["stockLabel"];
stockQty = stockInfo[productId]["stockQty"];
is_in_stock = stockInfo[productId]["is_in_stock"];
}
$$('#product_addtocart_form p.availability span').each(function(el) {
if(is_in_stock) {
$$('#product_addtocart_form p.availability').each(function(es) {
es.removeClassName('availability out-of-stock');
es.addClassName('availability in-stock');
});
el.innerHTML = /*stockQty + ' ' + */stockLabel;
} else {
$$('#product_addtocart_form p.availability').each(function(ef) {
ef.removeClassName('availability in-stock');
ef.addClassName('availability out-of-stock');
});
el.innerHTML = stockLabel;
}
});
};
Product.Config.prototype.updateProductShortDescription = function(productId) {
var shortDescription = this.config.shortDescription;
if (productId && this.config.shortDescriptions[productId].shortDescription) {
shortDescription = this.config.shortDescriptions[productId].shortDescription;
}
$$('#product_addtocart_form div.short-description div.std').each(function(el) {
el.innerHTML = shortDescription;
});
};
Product.Config.prototype.updateProductDescription = function(productId) {
var description = this.config.description;
if (productId && this.config.Descriptions[productId].Description) {
description = this.config.Descriptions[productId].Description;
}
$$('#product_tabs_description_tabbed_contents div.std').each(function(el) {
el.innerHTML = description;
});
};
Product.Config.prototype.updateProductAttributes = function(productId) {
var productAttributes = this.config.productAttributes;
if (productId && this.config.childProducts[productId].productAttributes) {
productAttributes = this.config.childProducts[productId].productAttributes;
}
//If config product doesn't already have an additional information section,
//it won't be shown for associated product either. It's too hard to work out
//where to place it given that different themes use very different html here
console.log(productAttributes) ;
$$('div.product-collateral div.attribs-info').each(function(el) {
el.innerHTML = productAttributes;
decorateTable('product-attribute-specs-table');
});
};
Product.Config.prototype.showCustomOptionsBlock = function(productId, parentId) {
var coUrl = this.config.ajaxBaseUrl + "co/?id=" + productId + '&pid=' + parentId;
var prodForm = $('product_addtocart_form');
if ($('SCPcustomOptionsDiv')==null) {
return;
}
Effect.Fade('SCPcustomOptionsDiv', { duration: 0.5, from: 1, to: 0.5 });
if(productId) {
//Uncomment the line below if you want an ajax loader to appear while any custom
//options are being loaded.
//$$('span.scp-please-wait').each(function(el) {el.show()});
//prodForm.getElements().each(function(el) {el.disable()});
new Ajax.Updater('SCPcustomOptionsDiv', coUrl, {
method: 'get',
evalScripts: true,
onComplete: function() {
$$('span.scp-please-wait').each(function(el) {el.hide()});
Effect.Fade('SCPcustomOptionsDiv', { duration: 0.5, from: 0.5, to: 1 });
//prodForm.getElements().each(function(el) {el.enable()});
}
});
} else {
$('SCPcustomOptionsDiv').innerHTML = '';
try{window.opConfig = new Product.Options([]);} catch(e){}
}
};
Product.OptionsPrice.prototype.reloadPriceLabels = function(productPriceIsKnown) {
var priceFromLabel = '';
var prodForm = $('product_addtocart_form');
if (!productPriceIsKnown && typeof spConfig != "undefined") {
priceFromLabel = spConfig.config.priceFromLabel;
}
var priceSpanId = 'configurable-price-from-' + this.productId;
var duplicatePriceSpanId = priceSpanId + this.duplicateIdSuffix;
if($(priceSpanId) && $(priceSpanId).select('span.configurable-price-from-label'))
$(priceSpanId).select('span.configurable-price-from-label').each(function(label) {
label.innerHTML = priceFromLabel;
});
if ($(duplicatePriceSpanId) && $(duplicatePriceSpanId).select('span.configurable-price-from-label')) {
$(duplicatePriceSpanId).select('span.configurable-price-from-label').each(function(label) {
label.innerHTML = priceFromLabel;
});
}
};
//SCP: Forces the 'next' element to have it's optionLabels reloaded too
Product.Config.prototype.configureElement = function(element) {
this.reloadOptionLabels(element);
if(element.value){
this.state[element.config.id] = element.value;
if(element.nextSetting){
element.nextSetting.disabled = false;
this.fillSelect(element.nextSetting);
this.reloadOptionLabels(element.nextSetting);
this.resetChildren(element.nextSetting);
}
}
else {
this.resetChildren(element);
}
this.reloadPrice();
};
//SCP: Changed logic to use absolute price ranges rather than price differentials
Product.Config.prototype.reloadOptionLabels = function(element){
var selectedPrice;
var childProducts = this.config.childProducts;
var stockInfo = this.config.stockInfo;
//Don't update elements that have a selected option
if(element.options[element.selectedIndex].config){
return;
}
for(var i=0;i<element.options.length;i++){
if(element.options[i].config){
var cheapestPid = this.getProductIdOfCheapestProductInScope("finalPrice", element.options[i].config.allowedProducts);
var mostExpensivePid = this.getProductIdOfMostExpensiveProductInScope("finalPrice", element.options[i].config.allowedProducts);
var cheapestFinalPrice = childProducts[cheapestPid]["finalPrice"];
var mostExpensiveFinalPrice = childProducts[mostExpensivePid]["finalPrice"];
var stock = '';
if(cheapestPid == mostExpensivePid ){
if(stockInfo[cheapestPid]["stockLabel"] != '') {
stock = '( ' +stockInfo[cheapestPid]["stockLabel"] + ' )';
}
}
if (this.config.showOutOfStock){
if(this.config.disable_out_of_stock_option ) {
if(!stockInfo[cheapestPid]["is_in_stock"] ) {
if(cheapestPid == mostExpensivePid ){
element.options[i].disabled=true;
var stock = '( ' +stockInfo[cheapestPid]["stockLabel"] + ' )';
}
}
}
}
var tierpricing = childProducts[mostExpensivePid]["tierpricing"];
element.options[i].text = this.getOptionLabel(element.options[i].config, cheapestFinalPrice, mostExpensiveFinalPrice, stock , tierpricing);
}
}
};
Product.Config.prototype.showTierPricingBlock = function(productId, parentId) {
var coUrl = this.config.ajaxBaseUrl + "co/?id=" + productId + '&pid=' + parentId;
var prodForm = $('product_addtocart_form');
if(productId) {
new Ajax.Updater('sppTierPricingDiv', coUrl, {
method: 'get',
evalScripts: true,
onComplete: function() {
$$('span.scp-please-wait').each(function(el) {el.hide()});
}
});
} else {
$('sppTierPricingDiv').innerHTML = '';
}
};
//SCP: Changed label formatting to show absolute price ranges rather than price differentials
Product.Config.prototype.getOptionLabel = function(option, lowPrice, highPrice, stock, tierpricing){
var str = option.label;
if(tierpricing > 0 && tierpricing < lowPrice) {
var tierpricinglowestprice = ': As low as (' + this.formatPrice(tierpricing,false) + ')';
} else {
var tierpricinglowestprice = '';
}
if (!this.config.showPriceRangesInOptions) {
return str;
}
if (!this.config.showOutOfStock){
stock = '';
}
lowPrices = this.getTaxPrices(lowPrice);
highPrices = this.getTaxPrices(highPrice);
if (this.config.hideprices) {
if (this.config.showOutOfStock){
return str + ' ' + stock + ' ';
} else {
return str;
}
}
var to = ' ' + this.config.rangeToLabel + ' ';
var separator = ': ( ';
if(lowPrice && highPrice){
if (this.config.showfromprice) {
this.config.priceFromLabel = this.config.priceFromLabel; //'From: ';
}
if (lowPrice != highPrice) {
if (this.taxConfig.showBothPrices) {
str+= separator + this.formatPrice(lowPrices[2], false) + ' (' + this.formatPrice(lowPrices[1], false) + ' ' + this.taxConfig.inclTaxTitle.replace('Tax','VAT') + ')';
str+= to + this.formatPrice(highPrices[2], false) + ' (' + this.formatPrice(highPrices[1], false) + ' ' + this.taxConfig.inclTaxTitle.replace('Tax','VAT') + ')';
str += " ) ";
} else {
str+= separator + this.formatPrice(lowPrices[0], false);
str+= to + this.formatPrice(highPrices[0], false);
str += " ) ";
}
} else {
if (this.taxConfig.showBothPrices) {
str+= separator + this.formatPrice(lowPrices[2], false) + ' (' + this.formatPrice(lowPrices[1], false) + ' ' + this.taxConfig.inclTaxTitle.replace('Tax','VAT') + ')';
str += " ) ";
str += stock;
str += tierpricinglowestprice;
} else {
if(tierpricing == 0 ) {
str+= separator + this.formatPrice(lowPrices[0], false);
str += " ) ";
}
str += tierpricinglowestprice;
str += ' ' + stock;
}
}
}
return str;
};
//SCP: Refactored price calculations into separate function
Product.Config.prototype.getTaxPrices = function(price) {
var price = parseFloat(price);
if (this.taxConfig.includeTax) {
var tax = price / (100 + this.taxConfig.defaultTax) * this.taxConfig.defaultTax;
var excl = price - tax;
var incl = excl*(1+(this.taxConfig.currentTax/100));
} else {
var tax = price * (this.taxConfig.currentTax / 100);
var excl = price;
var incl = excl + tax;
}
if (this.taxConfig.showIncludeTax || this.taxConfig.showBothPrices) {
price = incl;
} else {
price = excl;
}
return [price, incl, excl];
};
//SCP: Forces price labels to be updated on load
//so that first select shows ranges from the start
document.observe("dom:loaded", function() {
//Really only needs to be the first element that has configureElement set on it,
//rather than all.
if (typeof opConfig != "undefined") {
spConfig.reloadPrice();
}
$('product_addtocart_form').getElements().each(function(el) {
if(el.type == 'select-one') {
if(el.options && (el.options.length > 1)) {
el.options[0].selected = true;
spConfig.reloadOptionLabels(el);
}
}
});
});
Thank you
The version 1.5.11 is not compatible w/ Magento 1.9 according to the extension version on Magento connect. Please obtain the newest version of the extension and/or ask the creator to give you support. As far as I can see 1.9 support is support with 1.11.6, released 11th March 2015. The infos on their homepage and Magento connect are different - not good. On the homepage it says Works with Magento 1.9.0.X . tested 15 May 2014.
I need help ...
I have an autocomplete plugin that installed on my site and it works perfect...My need for autocomplete was bacause i have posts to which i want to redirect when clicked on autocompleted list item .
for example : i have one search form and when typed and autococompleted some post name then it redirects me to post like example.com/post/namePost .Now i cloned that website and my new website is example1.com ... now autocompleter in new site redirects me on autocomplete to example1.com/post/namePost .
My problem is , that i need that autocompleter on new site,redirects me to old website link - in this case www.example.com/post/postName. Note that after www.example.com both url data is same
Here is my autocomplete.js code :
/*
original jQuery plugin by http://www.pengoworks.com/workshop/jquery/autocomplete.htm
just replaced $ with jQuery in order to be complaint with other JavaScript libraries.
*/
jQuery.autocomplete = function(input, options) {
// Create a link to self
var me = this;
var link="http://telecoms-group.com/";
// Create jQuery object for input element
var $input = jQuery(input).attr("autocomplete", "off");
// Apply inputClass if necessary
if (options.inputClass) $input.addClass(options.inputClass);
// Create results
var results = document.createElement("div");
// Create jQuery object for results
var $results = jQuery(results);
$results.hide().addClass(options.resultsClass).css("position", "absolute");
if( options.width > 0 ) $results.css("width", options.width);
// Add to body element
jQuery("body").append(results);
input.autocompleter = me;
var timeout = null;
var prev = "";
var active = -1;
var cache = {};
var keyb = false;
var hasFocus = false;
var lastKeyPressCode = null;
// flush cache
function flushCache(){
cache = {};
cache.data = {};
cache.length = 0;
};
// flush cache
flushCache();
// if there is a data array supplied
if( options.data != null ){
var sFirstChar = "", stMatchSets = {}, row = [];
// no url was specified, we need to adjust the cache length to make sure it fits the local data store
if( typeof options.url != "string" ) options.cacheLength = 1;
// loop through the array and create a lookup structure
for( var i=0; i < options.data.length; i++ ){
// if row is a string, make an array otherwise just reference the array
row = ((typeof options.data[i] == "string") ? [options.data[i]] : options.data[i]);
// if the length is zero, don't add to list
if( row[0].length > 0 ){
// get the first character
sFirstChar = row[0].substring(0, 1).toLowerCase();
// if no lookup array for this character exists, look it up now
if( !stMatchSets[sFirstChar] ) stMatchSets[sFirstChar] = [];
// if the match is a string
stMatchSets[sFirstChar].push(row);
}
}
// add the data items to the cache
for( var k in stMatchSets ){
// increase the cache size
options.cacheLength++;
// add to the cache
addToCache(k, stMatchSets[k]);
}
}
$input
.keydown(function(e) {
// track last key pressed
lastKeyPressCode = e.keyCode;
switch(e.keyCode) {
case 38: // up
e.preventDefault();
moveSelect(-1);
break;
case 40: // down
e.preventDefault();
moveSelect(1);
break;
case 9: // tab
case 13: // return
if( selectCurrent() ){
// make sure to blur off the current field
$input.get(0).blur();
e.preventDefault();
}
break;
default:
active = -1;
if (timeout) clearTimeout(timeout);
timeout = setTimeout(function(){onChange();}, options.delay);
break;
}
})
.focus(function(){
// track whether the field has focus, we shouldn't process any results if the field no longer has focus
hasFocus = true;
})
.blur(function() {
// track whether the field has focus
hasFocus = false;
hideResults();
});
hideResultsNow();
function onChange() {
// ignore if the following keys are pressed: [del] [shift] [capslock]
if( lastKeyPressCode == 46 || (lastKeyPressCode > 8 && lastKeyPressCode < 32) ) return $results.hide();
var v = $input.val();
if (v == prev) return;
prev = v;
if (v.length >= options.minChars) {
$input.addClass(options.loadingClass);
requestData(v);
} else {
$input.removeClass(options.loadingClass);
$results.hide();
}
};
function moveSelect(step) {
var lis = jQuery("li", results);
if (!lis) return;
active += step;
if (active < 0) {
active = 0;
} else if (active >= lis.size()) {
active = lis.size() - 1;
}
lis.removeClass("ac_over");
jQuery(lis[active]).addClass("ac_over");
// Weird behaviour in IE
// if (lis[active] && lis[active].scrollIntoView) {
// lis[active].scrollIntoView(false);
// }
};
function selectCurrent() {
var li = jQuery("li.ac_over", results)[0];
if (!li) {
var $li = jQuery("li", results);
if (options.selectOnly) {
if ($li.length == 1) li = $li[0];
} else if (options.selectFirst) {
li = $li[0];
}
}
if (li) {
selectItem(li);
return true;
} else {
return false;
}
};
function selectItem(li) {
if (!li) {
li = document.createElement("li");
li.extra = [];
li.selectValue = "";
}
var v = jQuery.trim(li.selectValue ? li.selectValue : li.innerHTML);
input.lastSelected = v;
prev = v;
$results.html("");
$input.val(v);
hideResultsNow();
if (options.onItemSelect) setTimeout(function() { options.onItemSelect(li) }, 1);
};
// selects a portion of the input string
function createSelection(start, end){
// get a reference to the input element
var field = $input.get(0);
if( field.createTextRange ){
var selRange = field.createTextRange();
selRange.collapse(true);
selRange.moveStart("character", start);
selRange.moveEnd("character", end);
selRange.select();
} else if( field.setSelectionRange ){
field.setSelectionRange(start, end);
} else {
if( field.selectionStart ){
field.selectionStart = start;
field.selectionEnd = end;
}
}
field.focus();
};
// fills in the input box w/the first match (assumed to be the best match)
function autoFill(sValue){
// if the last user key pressed was backspace, don't autofill
if( lastKeyPressCode != 8 ){
// fill in the value (keep the case the user has typed)
$input.val($input.val() + sValue.substring(prev.length));
// select the portion of the value not typed by the user (so the next character will erase)
createSelection(prev.length, sValue.length);
}
};
function showResults() {
// get the position of the input field right now (in case the DOM is shifted)
var pos = findPos(input);
// either use the specified width, or autocalculate based on form element
var iWidth = (options.width > 0) ? options.width : $input.width();
// reposition
$results.css({
width: parseInt($input.width()+15)+ "px",
top: (pos.y + input.offsetHeight+ input.offsetHeight) + "px",
left: pos.x + "px"
}).show();
};
function hideResults() {
if (timeout) clearTimeout(timeout);
timeout = setTimeout(hideResultsNow, 200);
};
function hideResultsNow() {
if (timeout) clearTimeout(timeout);
$input.removeClass(options.loadingClass);
if ($results.is(":visible")) {
$results.hide();
}
if (options.mustMatch) {
var v = $input.val();
if (v != input.lastSelected) {
selectItem(null);
}
}
};
function receiveData(q, data) {
if (data) {
$input.removeClass(options.loadingClass);
results.innerHTML = "";
// if the field no longer has focus or if there are no matches, do not display the drop down
if( !hasFocus || data.length == 0 ) return hideResultsNow();
if (jQuery.browser.msie) {
// we put a styled iframe behind the calendar so HTML SELECT elements don't show through
$results.append(document.createElement('iframe'));
}
results.appendChild(dataToDom(data));
// autofill in the complete box w/the first match as long as the user hasn't entered in more data
if( options.autoFill && ($input.val().toLowerCase() == q.toLowerCase()) ) autoFill(data[0][0]);
showResults();
} else {
hideResultsNow();
}
};
function parseData(data) {
if (!data) return null;
var parsed = [];
var rows = data.split(options.lineSeparator);
for (var i=0; i < rows.length; i++) {
var row = jQuery.trim(rows[i]);
if (row) {
parsed[parsed.length] = row.split(options.cellSeparator);
}
}
return parsed;
};
function dataToDom(data) {
var ul = document.createElement("ul");
var num = data.length;
// limited results to a max number
if( (options.maxItemsToShow > 0) && (options.maxItemsToShow < num) ) num = options.maxItemsToShow;
for (var i=0; i < num; i++) {
var row = data[i];
if (!row) continue;
var li = document.createElement("li");
if (options.formatItem) {
li.innerHTML = options.formatItem(row, i, num);
li.selectValue = row[0];
} else {
li.innerHTML = row[0];
li.selectValue = row[0];
}
var extra = null;
if (row.length > 1) {
extra = [];
for (var j=1; j < row.length; j++) {
extra[extra.length] = row[j];
}
}
li.extra = extra;
ul.appendChild(li);
jQuery(li).hover(
function() { jQuery("li", ul).removeClass("ac_over"); jQuery(this).addClass("ac_over"); active = jQuery("li", ul).indexOf(jQuery(this).get(0)); },
function() { jQuery(this).removeClass("ac_over"); }
).click(function(e) { e.preventDefault(); e.stopPropagation(); selectItem(this) });
}
return ul;
};
function requestData(q) {
if (!options.matchCase) q = q.toLowerCase();
var data = options.cacheLength ? loadFromCache(q) : null;
// recieve the cached data
if (data) {
receiveData(q, data);
// if an AJAX url has been supplied, try loading the data now
} else if( (typeof options.url == "string") && (options.url.length > 0) ){
jQuery.get(makeUrl(q), function(data) {
data = parseData(data);
addToCache(q, data);
receiveData(q, data);
});
// if there's been no data found, remove the loading class
} else {
$input.removeClass(options.loadingClass);
}
};
function makeUrl(q) {
var url = options.url + "?q=" + encodeURI(q);
for (var i in options.extraParams) {
url += "&" + i + "=" + encodeURI(options.extraParams[i]);
}
return url;
};
function loadFromCache(q) {
if (!q) return null;
if (cache.data[q]) return cache.data[q];
if (options.matchSubset) {
for (var i = q.length - 1; i >= options.minChars; i--) {
var qs = q.substr(0, i);
var c = cache.data[qs];
if (c) {
var csub = [];
for (var j = 0; j < c.length; j++) {
var x = c[j];
var x0 = x[0];
if (matchSubset(x0, q)) {
csub[csub.length] = x;
}
}
return csub;
}
}
}
return null;
};
function matchSubset(s, sub) {
if (!options.matchCase) s = s.toLowerCase();
var i = s.indexOf(sub);
if (i == -1) return false;
return i == 0 || options.matchContains;
};
this.flushCache = function() {
flushCache();
};
this.setExtraParams = function(p) {
options.extraParams = p;
};
this.findValue = function(){
var q = $input.val();
if (!options.matchCase) q = q.toLowerCase();
var data = options.cacheLength ? loadFromCache(q) : null;
if (data) {
findValueCallback(q, data);
} else if( (typeof options.url == "string") && (options.url.length > 0) ){
jQuery.get(makeUrl(q), function(data) {
data = parseData(data)
addToCache(q, data);
findValueCallback(q, data);
});
} else {
// no matches
findValueCallback(q, null);
}
}
function findValueCallback(q, data){
if (data) $input.removeClass(options.loadingClass);
var num = (data) ? data.length : 0;
var li = null;
for (var i=0; i < num; i++) {
var row = data[i];
if( row[0].toLowerCase() == q.toLowerCase() ){
li = document.createElement("li");
if (options.formatItem) {
li.innerHTML = options.formatItem(row, i, num);
li.selectValue = row[0];
} else {
li.innerHTML = row[0];
li.selectValue = row[0];
}
var extra = null;
if( row.length > 1 ){
extra = [];
for (var j=1; j < row.length; j++) {
extra[extra.length] = row[j];
}
}
li.extra = extra;
}
}
if( options.onFindValue ) setTimeout(function() { options.onFindValue(li) }, 1);
}
function addToCache(q, data) {
if (!data || !q || !options.cacheLength) return;
if (!cache.length || cache.length > options.cacheLength) {
flushCache();
cache.length++;
} else if (!cache[q]) {
cache.length++;
}
cache.data[q] = data;
};
function findPos(obj) {
var curleft = obj.offsetLeft || 0;
var curtop = obj.offsetTop || 0;
while (obj = obj.offsetParent) {
curleft += obj.offsetLeft
curtop += obj.offsetTop
}
return {x:curleft,y:curtop};
}
}
jQuery.fn.autocomplete = function(url, options, data) {
// Make sure options exists
options = options || {};
// Set url as option
options.url = url;
// set some bulk local data
options.data = ((typeof data == "object") && (data.constructor == Array)) ? data : null;
// Set default values for required options
options.inputClass = options.inputClass || "ac_input";
options.resultsClass = options.resultsClass || "ac_results";
options.lineSeparator = options.lineSeparator || "\n";
options.cellSeparator = options.cellSeparator || "|";
options.minChars = options.minChars || 1;
options.delay = options.delay || 400;
options.matchCase = options.matchCase || 0;
options.matchSubset = options.matchSubset || 1;
options.matchContains = options.matchContains || 0;
options.cacheLength = options.cacheLength || 1;
options.mustMatch = options.mustMatch || 0;
options.extraParams = options.extraParams || {};
options.loadingClass = options.loadingClass || "ac_loading";
options.selectFirst = options.selectFirst || false;
options.selectOnly = options.selectOnly || false;
options.maxItemsToShow = options.maxItemsToShow || -1;
options.autoFill = options.autoFill || false;
options.width = parseInt(options.width, 10) || 0;
this.each(function() {
var input = this;
new jQuery.autocomplete(input, options);
});
// Don't break the chain
return this;
}
jQuery.fn.autocompleteArray = function(data, options) {
return this.autocomplete(null, options, data);
}
jQuery.fn.indexOf = function(e){
for( var i=0; i<this.length; i++ ){
if( this[i] == e ) return i;
}
return -1;
};
Can somebody tell me where is that part with url redirection , and how can i change that
I'm working on a calculator that takes an expression such as (5+4) and evaluates it by passing the buttons pressed to an array, and then building a parse tree from the data in the array.
What's interesting/strange, is that my code won't push the value of the right parenthesis to the array. Here is my code, could someone help me out?
The console.log activeButton shows that is the value of the button being pressed, but even when I placed calcArray.push() outside the if statements it would not push ) to an array.
$(document).ready(function(){
var calcArray = new Array();
$("input").click(function(){
var activeButton = this.value;
console.log(activeButton);
if(!isNaN(activeButton))
{
calcArray.push(parseInt(activeButton));
console.log(calcArray);
}
else if(activeButton === "=")
{
evaluate(buildTree(calcArray));
calcArray = [];
}
else
{
calcArray.push(activeButton);
}
});
});
The BuildTree code:
function BinaryTree(root) {
this.root = root;
this.activeNode = root;
}
function Node(element){
this.element = element;
this.parent;
this.rightChild;
this.leftChild;
this.setLeft = function(node){
this.leftChild = node;
node.parent = this;
};
this.setRight = function(node){
this.rightChild = node;
node.parent = this;
};
}
//methods
var buildTree = function(array)
{
var tree = new BinaryTree(new Node(null));
for(var i = 0; i < array.length; i++)
{
var newNode = new Node(array[i]);
if(array[i] == "(")
{
newNode.element = null;
tree.activeNode.setLeft(newNode);
tree.activeNode = newNode;
}
else if(array[i] == "+" || array[i] == "-" || array[i] == "/" || array[i] == "*")
{
tree.activeNode.element = newNode.element;
tree.activeNode.setRight(new Node(null));
tree.activeNode = tree.activeNode.rightChild;
}
else if(array[i] == ")")
{
if(tree.activeNode.parent == null)
{
;
}
else
{
tree.activeNode = tree.activeNode.parent;
tree.root = tree.activeNode;
}
}
else
{
tree.activeNode.element = newNode.element;
tree.activeNode = tree.activeNode.parent;
}
}
return tree.activeNode;
}
var evaluate = function(node){
var newNode1, newNode2;
newNode1 = new Node(null);
newNode1.parent = node;
newNode2 = new Node(null);
newNode2.parent = node;
if(node.leftChild == null && node.rightChild == null)
return node.element;
else{
newNode1.element = evaluate(node.leftChild);
newNode2.element = evaluate(node.rightChild);
if(newNode1.parent.element == "+")
{
return Number(newNode1.element) + Number(newNode2.element);
}
if(newNode1.parent.element == "-")
{
return newNode1.element - newNode2.element;
}
if(newNode1.parent.element == "*")
{
return newNode1.element * newNode2.element;
}
else
{
return newNode1.element / newNode2.element;
}
}
};
I just tried this out using your code and it worked fine passing the value as a string:
function pushButton (value) {
var activeButton = value;
console.log(activeButton);
if(!isNaN(activeButton))
{
calcArray.push(parseInt(activeButton));
console.log(calcArray);
}
else if(activeButton === "=")
{
evaluate(buildTree(calcArray));
calcArray = [];
}
else
{
calcArray.push(activeButton);
}
};
You aren't ever printing out the array in the last case (which is where the right paren would go), so are you sure it's not on the array and you just aren't seeing the visual feedback?
If so, we need to see more of your code. Try and setup a jsfiddle.
This is my first post on StackOverflow and might I say, what a great and helpful resource this is. I have been able to find many answers to my questions and hope to do the same with this one. On to the issue at hand... I am currently using the instafeed.js (http://instafeedjs.com/) script to pull in images from instagram and display them on my site.
What I'm trying to accomplish is to have 9 items display, then if I hit the "next" button, it would replace the current 9 images and load the next 9 images and, if the "previous" button is clicked it would go back and show the previous 9 images.
Currently it only renders one image thumb that scrolls through 9 images then stops. Swapping only the one image at a time. A sample of the current working code with only 1 image displaying can be found here - http://codepen.io/stevenschobert/pen/iHxfw
Here is my JavaScript for the instafeed call:
var count = 1;
var feed;
feed = new Instafeed({
clientId: '68be8b63013048ff81bb4ac8b02b606e',
limit: 9,
resolution: 'standard_resolution',
template: '<img src="{{image}}" /><div class="likes">♥ {{likes}}</div>',
mock: true,
after: function () {
var images = $("#instafeed").find('a');
$.each(images, function(index, image) {
var delay = (index * 75) + 'ms';
$(image).css('-webkit-animation-delay', delay);
$(image).css('-moz-animation-delay', delay);
$(image).css('-ms-animation-delay', delay);
$(image).css('-o-animation-delay', delay);
$(image).css('animation-delay', delay);
$(image).addClass('animated fadeInUp pic-'+count++);
});
},
custom: {
images: [],
currentImage: 0,
showImage: function () {
var result, image;
image = this.options.custom.images[this.options.custom.currentImage];
result = this._makeTemplate(this.options.template, {
model: image,
id: image.id,
link: image.link,
image: image.images[this.options.resolution].url,
caption: this._getObjectProperty(image, 'caption.text'),
likes: image.likes.count,
comments: image.comments.count,
location: this._getObjectProperty(image, 'location.name')
});
$("#instafeed").html(result);
}
},
success: function (data) {
this.options.custom.images = data.data;
this.options.custom.showImage.call(this);
}
});
feed.run();
$(".next").click(function () {
var length, current;
current = feed.options.custom.currentImage;
length = feed.options.custom.images.length;
if (current < length - 1) {
feed.options.custom.currentImage++;
feed.options.custom.showImage.call(feed);
}
});
$(".prev").click(function () {
var length, current;
current = feed.options.custom.currentImage;
length = feed.options.custom.images.length;
if (current > 0) {
feed.options.custom.currentImage--
feed.options.custom.showImage.call(feed);
}
});
My HTML:
<div id="instafeed"></div>
<div class="controls">
<div class="prev"><- prev</div>
<div class="next">next -></div>
</div>
The Instafeed.js code:
(function() { var Instafeed, root; Instafeed = (function() {
function Instafeed(params) {
var option, value;
this.options = {
target: 'instafeed',
get: 'popular',
resolution: 'thumbnail',
sortBy: 'most-recent',
links: true,
limit: 15,
mock: false
};
if (typeof params === 'object') {
for (option in params) {
value = params[option];
this.options[option] = value;
}
}
this.unique = this._genKey();
}
Instafeed.prototype.run = function() {
var header, instanceName, script;
if (typeof this.options.clientId !== 'string') {
if (typeof this.options.accessToken !== 'string') {
throw new Error("Missing clientId or accessToken.");
}
}
if (typeof this.options.accessToken !== 'string') {
if (typeof this.options.clientId !== 'string') {
throw new Error("Missing clientId or accessToken.");
}
}
if ((this.options.before != null) && typeof this.options.before === 'function') {
this.options.before.call(this);
}
if (typeof document !== "undefined" && document !== null) {
script = document.createElement('script');
script.id = 'instafeed-fetcher';
script.src = this._buildUrl();
header = document.getElementsByTagName('head');
header[0].appendChild(script);
instanceName = "instafeedCache" + this.unique;
window[instanceName] = new Instafeed(this.options);
window[instanceName].unique = this.unique;
}
return true;
};
Instafeed.prototype.parse = function(response) {
var anchor, fragment, header, htmlString, image, imageString, images, img, instanceName, reverse, sortSettings, _i, _j, _len, _len1;
if (typeof response !== 'object') {
if ((this.options.error != null) && typeof this.options.error === 'function') {
this.options.error.call(this, 'Invalid JSON data');
return false;
} else {
throw new Error('Invalid JSON response');
}
}
if (response.meta.code !== 200) {
if ((this.options.error != null) && typeof this.options.error === 'function') {
this.options.error.call(this, response.meta.error_message);
return false;
} else {
throw new Error("Error from Instagram: " + response.meta.error_message);
}
}
if (response.data.length === 0) {
if ((this.options.error != null) && typeof this.options.error === 'function') {
this.options.error.call(this, 'No images were returned from Instagram');
return false;
} else {
throw new Error('No images were returned from Instagram');
}
}
if ((this.options.success != null) && typeof this.options.success === 'function') {
this.options.success.call(this, response);
}
if (this.options.sortBy !== 'most-recent') {
if (this.options.sortBy === 'random') {
sortSettings = ['', 'random'];
} else {
sortSettings = this.options.sortBy.split('-');
}
reverse = sortSettings[0] === 'least' ? true : false;
switch (sortSettings[1]) {
case 'random':
response.data.sort(function() {
return 0.5 - Math.random();
});
break;
case 'recent':
response.data = this._sortBy(response.data, 'created_time', reverse);
break;
case 'liked':
response.data = this._sortBy(response.data, 'likes.count', reverse);
break;
case 'commented':
response.data = this._sortBy(response.data, 'comments.count', reverse);
break;
default:
throw new Error("Invalid option for sortBy: '" + this.options.sortBy + "'.");
}
}
if ((typeof document !== "undefined" && document !== null) && this.options.mock === false) {
document.getElementById(this.options.target).innerHTML = '';
images = response.data;
if (images.length > this.options.limit) {
images = images.slice(0, this.options.limit + 1 || 9e9);
}
if ((this.options.template != null) && typeof this.options.template === 'string') {
htmlString = '';
imageString = '';
for (_i = 0, _len = images.length; _i < _len; _i++) {
image = images[_i];
imageString = this._makeTemplate(this.options.template, {
model: image,
id: image.id,
link: image.link,
image: image.images[this.options.resolution].url,
caption: this._getObjectProperty(image, 'caption.text'),
likes: image.likes.count,
comments: image.comments.count,
location: this._getObjectProperty(image, 'location.name')
});
htmlString += imageString;
}
document.getElementById(this.options.target).innerHTML = htmlString;
} else {
fragment = document.createDocumentFragment();
for (_j = 0, _len1 = images.length; _j < _len1; _j++) {
image = images[_j];
img = document.createElement('img');
img.src = image.images[this.options.resolution].url;
if (this.options.links === true) {
anchor = document.createElement('a');
anchor.href = image.images['standard_resolution'].url;
anchor.rel = "lightbox";
anchor.appendChild(img);
fragment.appendChild(anchor);
} else {
fragment.appendChild(img);
}
}
document.getElementById(this.options.target).appendChild(fragment);
}
header = document.getElementsByTagName('head')[0];
header.removeChild(document.getElementById('instafeed-fetcher'));
instanceName = "instafeedCache" + this.unique;
delete window[instanceName];
}
if ((this.options.after != null) && typeof this.options.after === 'function') {
this.options.after.call(this);
}
return true;
};
Instafeed.prototype._buildUrl = function() {
var base, endpoint, final;
base = "https://api.instagram.com/v1";
switch (this.options.get) {
case "popular":
endpoint = "media/popular";
break;
case "tagged":
if (typeof this.options.tagName !== 'string') {
throw new Error("No tag name specified. Use the 'tagName' option.");
}
endpoint = "tags/" + this.options.tagName + "/media/recent";
break;
case "location":
if (typeof this.options.locationId !== 'number') {
throw new Error("No location specified. Use the 'locationId' option.");
}
endpoint = "locations/" + this.options.locationId + "/media/recent";
break;
case "user":
if (typeof this.options.userId !== 'number') {
throw new Error("No user specified. Use the 'userId' option.");
}
if (typeof this.options.accessToken !== 'string') {
throw new Error("No access token. Use the 'accessToken' option.");
}
endpoint = "users/" + this.options.userId + "/media/recent";
break;
default:
throw new Error("Invalid option for get: '" + this.options.get + "'.");
}
final = "" + base + "/" + endpoint;
if (this.options.accessToken != null) {
final += "?access_token=" + this.options.accessToken;
} else {
final += "?client_id=" + this.options.clientId;
}
final += "&count=" + this.options.limit;
final += "&callback=instafeedCache" + this.unique + ".parse";
return final;
};
Instafeed.prototype._genKey = function() {
var S4;
S4 = function() {
return (((1 + Math.random()) * 0x10000) | 0).toString(16).substring(1);
};
return "" + (S4()) + (S4()) + (S4()) + (S4());
};
Instafeed.prototype._makeTemplate = function(template, data) {
var output, pattern, varName, varValue, _ref;
pattern = /(?:\{{2})([\w\[\]\.]+)(?:\}{2})/;
output = template;
while (pattern.test(output)) {
varName = output.match(pattern)[1];
varValue = (_ref = this._getObjectProperty(data, varName)) != null ? _ref : '';
output = output.replace(pattern, "" + varValue);
}
return output;
};
Instafeed.prototype._getObjectProperty = function(object, property) {
var piece, pieces;
property = property.replace(/\[(\w+)\]/g, '.$1');
pieces = property.split('.');
while (pieces.length) {
piece = pieces.shift();
if ((object != null) && piece in object) {
object = object[piece];
} else {
return null;
}
}
return object;
};
Instafeed.prototype._sortBy = function(data, property, reverse) {
var sorter;
sorter = function(a, b) {
var valueA, valueB;
valueA = this._getObjectProperty(a, property);
valueB = this._getObjectProperty(b, property);
if (reverse) {
if (valueA > valueB) {
return 1;
} else {
return -1;
}
}
if (valueA < valueB) {
return 1;
} else {
return -1;
}
};
data.sort(sorter.bind(this));
return data;
};
return Instafeed;})(); root = typeof exports !== "undefined" && exports !== null ? exports : window; root.Instafeed = Instafeed;}).call(this);
Any help with this issue would be GREATLY appreciated.
Thank You,
Jason
I've been debugging the ReportingServices.js file using Firefox and Firebug. I've found that the reason SSRS (SQL Server Reporting Services) Report Manager (web front end for Reports) doesn't work in Firefox (v7.0.1) is that it's using javascript .lastChild to find elements. Unfortunately, Firefox also picks up on whitespace as TextNode elements causing the element selection to not work as expected.
This works in IE and hopefully someone knows a solution to this. I edited the javascript to get round one bug but then hit another more complicated one so probably a mine field to try to fix manually. Hopefully there is some update or patch available.
This is running SQL Server 2008 R2 Standard edition on a Windows 2008 R2 Datacenter server.
Apologies if you feel this is not the forum for such a question. In that case, please suggest where else I should ask the question if it's not appropriate. It is kindof a javascript problem but likely with a software update solution.
Updated:
After a few hours of fixing the browser compatibility bugs in the ReportingServices.js file I managed to get it to work on Firefox, Chrome, Opera and Safari as well as IE. Sorry that my answer below is in 2 parts; I posted the entire code of the updated ReportingServices.js for the solution.
After a few hours hacking around with the original ReportingServices.js file I managed to fix the javascript to work on Firefox, Chrome, Opera and Safari as well as IE.
Even though it's a bit big I've posted the whole edited ReportingServices.js below for others to use if needed. I've put "chris edit" comments showing the old lines above their edits so you can (if you care) follow what I've changed. I've also summarized these changes at the top of the code.
The SSRS report manager web interface is very useful and it would be a shame not to use it just because Microsoft didn't bother to test it on other browsers than IE. This is why I always prefer jQuery over plain javascript to avoid these kind of cross browser compatibility issues.
I had to post it in 2 parts. Hope this helps others!
/*
Author: Chris Snowden
Modified Date: 21st October 2011
ReportingServices.js file for SQL Server 2008 R2 Reporting Services
Updated to fix a bug whereby drop down context menus didn't work
for any other browser than IE.
1) I added functions to find firstChild and lastChild while skipping any
whitespace TextNode elements.
2) I updated the Clicked function to get at the table element value in a way
that works for firefox.
3) I updated the SplitContextMenuConfigString function to access the table
cells by first looping through each row and then the cells.
Drop downs now work on Firefox, Chrome, Opera and Safari as well as IE.
*/
var checkBoxCount;
var checkBoxId;
var checkBoxHead;
// Context menu
var _divContextMenu; // The container for the context menu
var _selectedIdHiddenField; // The id of the item that opened th context menu
var _timeOutLimit = 3000; // How long the context menu stays for after the cursor in no longer over it
var _timeOutTimer; // The timout for the context menu
var _itemSelected = false;
var _mouseOverContext = false; // If the mouse is over the context menu
var _contextMenusIds; // The array of the diffrent context menus
var _fadeTimeouts; // The array of timouts used for the fade effect
var _onLink = false; // If the user is over a name link
var _selectedItemId;
var _tabFocusedItem = '';
var _mouseOverItem = '';
var _unselectedItemStyle;
var _currentContextMenuId; // ID of currently displayed context menu
var _currentMenuItemId = null; // ID of currently selected context menu item
// Search bar
var _searchTextBoxID;
var _defaultSearchValue; // The value that the box defaults to.
// start chris edit
// new functions to find firstChild and lastChild but skipping whitespace elements
function firstChildNoWS(element) {
var child = element.firstChild;
while (child != null && child.isElementContentWhitespace) {
child = child.nextSibling;
}
return child;
}
function lastChildNoWS(element) {
var child = element.lastChild;
while (child != null && child.isElementContentWhitespace) {
child = child.previousSibling;
}
return child;
}
// end chris edit
function ToggleItem(itemId) {
var item = document.getElementById(itemId);
if (item.style.display == 'none')
item.style.display = 'inline';
else
item.style.display = 'none';
}
function ToggleButtonImage(image1ID, image2ID) {
var image1 = document.getElementById(image1ID);
var image2 = document.getElementById(image2ID);
if (image1.style.display == 'none') {
image1.style.display = 'inline-block';
image2.style.display = 'none';
}
else {
image1.style.display = 'none';
image2.style.display = 'inline-block';
}
}
function SetFocus(id) {
var obj = document.getElementById(id);
if (obj != null && !obj.disabled)
obj.focus();
}
// Validates that an extension has been selected
function ValidateDropDownSelection(source, args) {
var obj = document.getElementById(source.controltovalidate);
if (obj.options[0].selected && !obj.disabled)
args.IsValid = false;
else
args.IsValid = true;
}
/// selectAll
/// selects all the checkBoxes with the given id
function selectAll() {
var i;
var id;
var checked = checkBoxHead.checked;
for (i = 0; i < checkBoxCount; i++) {
id = checkBoxId + i;
document.getElementById(id).checked = checked;
}
}
/// onSglCheck
/// performs actions when a single checkBox is checked or unchecked
/// cb -> the checkBox generating the event
/// topId -> id of the "select all" checkBox
function onSglCheck() {
// uncheck the top checkBox
checkBoxHead.checked = false;
}
/// ToggleButton
/// Toggle a buttons enable state
function ToggleButton(id, disabled) {
if (document.getElementById(id) != null)
document.getElementById(id).disabled = disabled;
}
function ToggleValidator(id, enabled) {
document.getElementById(id).enabled = enabled;
}
function SetCbVars(cbid, count, cbh) {
checkBoxCount = count;
checkBoxId = cbid;
checkBoxHead = cbh;
}
/// Check to see if any check boxes should disable
/// a control
/// cbid -> id prefix of the checkBoxes
/// cbCount -> total checkBoxes to check
/// hidden -> input to look for
/// display -> control to disable
function CheckCheckBoxes(cbid, hidden, display) {
var i;
var id;
var disable;
disable = false;
for (i = 0; i < checkBoxCount; i++) {
id = cbid + i;
if (document.getElementById(id).checked) {
id = hidden + id;
if (document.getElementById(id) != null) {
disable = true;
break;
}
}
}
ToggleButton(display, disable);
}
function HiddenCheckClickHandler(hiddenID, promptID, promptStringID) {
var hiddenChk = document.getElementById(hiddenID);
var promptChk = document.getElementById(promptID);
// prompt should be in opposite state of hidden
promptChk.checked = !hiddenChk.checked;
}
function validateSaveRole(source, args) {
var i;
var id;
var c = 0;
for (i = 0; i < checkBoxCount; i++) {
id = checkBoxId + i;
if (document.getElementById(id).checked) c++;
}
if (0 == c)
args.IsValid = false;
else
args.IsValid = true;
}
/// Pad an integer less then 10 with a leading zero
function PadIntWithZero(val) {
var s = val.toString();
if (val < 10 && val >= 0) {
if (s.length == 1)
s = "0" + s;
else if (s.length > 2)
s = s.substring(s.length - 2, s.length);
}
return s;
}
/// Pad the contents of an input with leading zeros if necesarry
function PadInputInteger(id) {
document.getElementById(id).value = PadIntWithZero(document.getElementById(id).value);
}
/// text of confirmation popup when a single item is selected for deletion
/// e.g. "Are you sure you want to delete this item"
var confirmSingle;
/// text of confirmation popup when multiple items are selected for deletion
/// e.g. "Are you sure you want to delete these items"
var confirmMultiple;
function SetDeleteTxt(single, multiple) {
confirmSingle = single;
confirmMultiple = multiple;
}
/// doCmDel: DoConfirmDelete
/// Given a number of checked items, confirm their deletion
/// return true if OK was clicked; false otherwise
function doCmDel(checkedCount) {
var confirmTxt = confirmSingle;
if (checkedCount == 0)
return false;
if (checkedCount > 1)
confirmTxt = confirmMultiple;
return confirm(confirmTxt);
}
/// on non-Netscape browsers, confirm deletion of 0 or more items
function confirmDelete() {
return doCmDel(getChkCount());
}
/// confirm deletion of policies
function confirmDeletePlcies(alertString) {
var count = getChkCount();
if (count >= checkBoxCount) {
alert(alertString);
return false;
}
return doCmDel(count);
}
/// counts whether 0, 1, or more than 1 checkboxes are checked
/// returns 0, 1, or 2
function getChkCount() {
var checkedCount = 0;
for (i = 0; i < checkBoxCount && checkedCount < 2; i++) {
if (document.getElementById(checkBoxId + i).checked) {
checkedCount++;
}
}
return checkedCount;
}
function ToggleButtonBasedOnCheckBox(checkBoxId, toggleId, reverse) {
var chkb = document.getElementById(checkBoxId);
if (chkb != null) {
if (chkb.checked == true)
ToggleButton(toggleId, reverse); // enable if reverse == false
else
ToggleButton(toggleId, !reverse); // disable if reverse == false
}
}
function ToggleButtonBasedOnCheckBoxWithOverride(checkBoxId, toggleId, overrideToDisabled, reverse) {
if (overrideToDisabled == true)
ToggleButton(toggleId, true); // disable
else
ToggleButtonBasedOnCheckBox(checkBoxId, toggleId, reverse);
}
function ToggleButtonBasedOnCheckBoxes(checkBoxId, checkboxId2, toggleId) {
var chkb = document.getElementById(checkBoxId);
if (chkb != null) {
if (chkb.checked == true)
ToggleButtonBasedOnCheckBox(checkboxId2, toggleId, false);
else
ToggleButton(toggleId, true); // disable
}
}
function ToggleButtonBasedOnCheckBoxesWithOverride(checkBoxId, checkboxId2, toggleId, overrideToDisabled) {
if (overrideToDisabled == true)
ToggleButton(toggleId, true); // disable
else
ToggleButtonBasedOnCheckBoxes(checkBoxId, checkboxId2, toggleId);
}
function ToggleValidatorBasedOnCheckBoxWithOverride(checkBoxId, toggleId, overrideToDisabled, reverse) {
if (overrideToDisabled == true)
ToggleValidator(toggleId, false);
else {
var chkb = document.getElementById(checkBoxId);
if (chkb != null) {
ToggleValidator(toggleId, chkb.checked != reverse);
}
}
}
function ToggleValidatorBasedOnCheckBoxesWithOverride(checkBoxId, checkBoxId2, toggleId, overrideToDisabled, reverse) {
if (overrideToDisabled == true)
ToggleValidator(toggleId, false);
else {
var chkb = document.getElementById(checkBoxId);
if (chkb != null) {
if (chkb.checked == reverse)
ToggleValidator(toggleId, false);
else
ToggleValidatorBasedOnCheckBoxWithOverride(checkBoxId2, toggleId, overrideToDisabled, reverse);
}
}
}
function CheckButton(buttonID, shouldCheck) {
document.getElementById(buttonID).checked = shouldCheck;
}
function EnableMultiButtons(prefix) {
// If there are no multibuttons, there is no reason to iterate the
// list of checkboxes.
if (checkBoxCount == 0 || multiButtonList.length == 0)
return;
var enableMultiButtons = false;
var multipleCheckboxesSelected = false;
// If the top level check box is checked, we know the state of all
// of the checkboxes
var headerCheckBox = document.getElementById(prefix + "ch");
if (headerCheckBox != null && headerCheckBox.checked) {
enableMultiButtons = true;
multipleCheckboxesSelected = checkBoxCount > 1;
}
else {
// Look at each checkbox. If any one of them is checked,
// enable the multi buttons.
var foundOneChecked = false;
var i;
for (i = 0; i < checkBoxCount; i++) {
var checkBox = document.getElementById(prefix + 'cb' + i);
if (checkBox.checked) {
if (foundOneChecked) {
multipleCheckboxesSelected = true;
break;
}
else {
enableMultiButtons = true;
foundOneChecked = true;
}
}
}
}
// Enable/disable each of the multi buttons
var j;
for (j = 0; j < multiButtonList.length; j++) {
var button = document.getElementById(multiButtonList[j]);
if (button.allowMultiSelect)
button.disabled = !enableMultiButtons;
else
button.disabled = !enableMultiButtons || multipleCheckboxesSelected;
}
}
//function ShadowCopyPassword(suffix)
function MarkPasswordFieldChanged(suffix) {
if (event.propertyName == "value") {
var pwdField = document.getElementById("ui_txtStoredPwd" + suffix);
//var shadowField = document.getElementById("ui_shadowPassword" + suffix);
var shadowChanged = document.getElementById("ui_shadowPasswordChanged" + suffix);
// Don't shadow copy during initialization
if (pwdField.IsInit) {
//shadowField.value = pwdField.value;
//pwdField.UserEnteredPassword = "true";
shadowChanged.value = "true";
// Update validator state (there is no validator on the data driven subscription page)
var validator = document.getElementById("ui_validatorPassword" + suffix)
if (validator != null)
ValidatorValidate(validator);
}
}
}
function InitDataSourcePassword(suffix) {
var pwdField = document.getElementById("ui_txtStoredPwd" + suffix);
var shadowChanged = document.getElementById("ui_shadowPasswordChanged" + suffix);
// var shadowField = document.getElementById("ui_shadowPassword" + suffix);
var storedRadioButton = document.getElementById("ui_rdoStored" + suffix);
var pwdValidator = document.getElementById("ui_validatorPassword" + suffix);
pwdField.IsInit = false;
// Initialize the field to the shadow value (for when the user clicks back/forward)
// Or to a junk initial value.
if (pwdValidator != null && storedRadioButton.checked) {
/* if (shadowField.value.length > 0)
pwdField.value = shadowField.value;
else*/
pwdField.value = "********";
}
else
shadowChanged.value = "true"; // shadowChanged will be ignored if the page is submitted without storedRadioButton.checked
// Now that the initial value is set, track changes to the password field
pwdField.IsInit = true;
// There is no validator on the data driven subscription page (no stored radio button either)
if (pwdValidator != null)
ValidatorValidate(pwdValidator);
}
function SetNeedPassword(suffix) {
// Set a flag indicating that we need the password
var pwdField = document.getElementById("ui_txtStoredPwd" + suffix);
pwdField.NeedPassword = "true";
// Make the validator visible
ValidatorValidate(document.getElementById("ui_validatorPassword" + suffix));
}
function UpdateValidator(src, validatorID) {
if (src.checked) {
var validator = document.getElementById(validatorID);
ValidatorValidate(validator);
}
}
function ReEnterPasswordValidation(source, arguments) // source = validator
{
var validatorIdPrefix = "ui_validatorPassword"
var suffix = source.id.substr(validatorIdPrefix.length, source.id.length - validatorIdPrefix.length);
var storedRadioButton = document.getElementById("ui_rdoStored" + suffix);
var pwdField = document.getElementById("ui_txtStoredPwd" + suffix);
var shadowChanged = document.getElementById("ui_shadowPasswordChanged" + suffix);
var customDataSourceRadioButton = document.getElementById("ui_rdoCustomDataSource" + suffix);
var isCustomSelected = true;
if (customDataSourceRadioButton != null)
isCustomSelected = customDataSourceRadioButton.checked;
if (!isCustomSelected || // If the custom (vs shared) data source radio button exists and is not selected, we don't need the pwd.
storedRadioButton.checked == false || // If the data source is not using stored credentials, we don't need the password
pwdField.UserEnteredPassword == "true" || // If the password has changed, we don't need to get it from the user
pwdField.NeedPassword != "true" || // If no credentials have changed, we don't need the password
shadowChanged.value == "true") // If the user has typed a password
arguments.IsValid = true;
else
arguments.IsValid = false;
}
function ValidateDataSourceSelected(source, arguments) {
var validatorIdPrefix = "ui_sharedDSSelectedValidator"
var suffix = source.id.substr(validatorIdPrefix.length, source.id.length - validatorIdPrefix.length);
var sharedRadioButton = document.getElementById("ui_rdoSharedDataSource" + suffix);
var hiddenField = document.getElementById("ui_hiddenSharedDS" + suffix);
arguments.IsValid = (sharedRadioButton != null && !sharedRadioButton.checked) || hiddenField.value != "NotSelected";
}
/**************************************************************************/
// MultiValueParamClass
function MultiValueParamClass(thisID, visibleTextBoxID, floatingEditorID, floatingIFrameID, paramObject,
hasValidValues, allowBlank, doPostbackOnHide, postbackScript) {
this.m_thisID = thisID;
this.m_visibleTextBoxID = visibleTextBoxID;
this.m_floatingEditorID = floatingEditorID;
this.m_floatingIFrameID = floatingIFrameID;
this.m_paramObject = paramObject;
this.m_hasValidValues = hasValidValues;
this.m_allowBlank = allowBlank;
this.m_doPostbackOnHide = doPostbackOnHide;
this.m_postbackScript = postbackScript;
this.UpdateSummaryString();
}
function ToggleVisibility() {
var floatingEditor = GetControl(this.m_floatingEditorID);
if (floatingEditor.style.display != "inline")
this.Show();
else
this.Hide();
}
MultiValueParamClass.prototype.ToggleVisibility = ToggleVisibility;
function Show() {
var floatingEditor = GetControl(this.m_floatingEditorID);
if (floatingEditor.style.display == "inline")
return;
// Set the correct size of the floating editor - no more than
// 150 pixels high and no less than the width of the text box
var visibleTextBox = GetControl(this.m_visibleTextBoxID);
if (this.m_hasValidValues) {
if (floatingEditor.offsetHeight > 150)
floatingEditor.style.height = 150;
floatingEditor.style.width = visibleTextBox.offsetWidth;
}
var newEditorPosition = this.GetNewFloatingEditorPosition();
floatingEditor.style.left = newEditorPosition.Left;
floatingEditor.style.top = newEditorPosition.Top;
floatingEditor.style.display = "inline";
var floatingIFrame = GetControl(this.m_floatingIFrameID);
floatingIFrame.style.left = floatingEditor.style.left;
floatingIFrame.style.top = floatingEditor.style.top;
floatingIFrame.style.width = floatingEditor.offsetWidth;
floatingIFrame.style.height = floatingEditor.offsetHeight;
floatingIFrame.style.display = "inline";
// If another multi value is open, close it first
if (this.m_paramObject.ActiveMultValue != this && this.m_paramObject.ActiveMultiValue != null)
ControlClicked(this.m_paramObject.id);
this.m_paramObject.ActiveMultiValue = this;
if (floatingEditor.childNodes[0].focus) floatingEditor.childNodes[0].focus();
this.StartPolling();
}
MultiValueParamClass.prototype.Show = Show;
function Hide() {
var floatingEditor = GetControl(this.m_floatingEditorID);
var floatingIFrame = GetControl(this.m_floatingIFrameID);
// Hide the editor
floatingEditor.style.display = "none";
floatingIFrame.style.display = "none";
this.UpdateSummaryString();
if (this.m_doPostbackOnHide)
eval(this.m_postbackScript);
// Check that the reference is still us in case event ordering
// caused another multivalue to click open
if (this.m_paramObject.ActiveMultiValue == this)
this.m_paramObject.ActiveMultiValue = null;
}
MultiValueParamClass.prototype.Hide = Hide;
function GetNewFloatingEditorPosition() {
// Make the editor visible
var visibleTextBox = GetControl(this.m_visibleTextBoxID);
var textBoxPosition = GetObjectPosition(visibleTextBox);
return { Left: textBoxPosition.Left, Top: textBoxPosition.Top + visibleTextBox.offsetHeight };
}
MultiValueParamClass.prototype.GetNewFloatingEditorPosition = GetNewFloatingEditorPosition;
function UpdateSummaryString() {
var summaryString;
if (this.m_hasValidValues)
summaryString = GetValueStringFromValidValueList(this.m_floatingEditorID);
else
summaryString = GetValueStringFromTextEditor(this.m_floatingEditorID, false, this.m_allowBlank);
var visibleTextBox = GetControl(this.m_visibleTextBoxID);
visibleTextBox.value = summaryString;
}
MultiValueParamClass.prototype.UpdateSummaryString = UpdateSummaryString;
function StartPolling() {
setTimeout(this.m_thisID + ".PollingCallback();", 100);
}
MultiValueParamClass.prototype.StartPolling = StartPolling;
function PollingCallback() {
// If the editor isn't visible, no more events.
var floatingEditor = GetControl(this.m_floatingEditorID);
if (floatingEditor.style.display != "inline")
return;
// If the text box moved, something on the page resized, so close the editor
var expectedEditorPos = this.GetNewFloatingEditorPosition();
if (floatingEditor.style.left != expectedEditorPos.Left + "px" ||
floatingEditor.style.top != expectedEditorPos.Top + "px") {
this.Hide();
}
else {
this.StartPolling();
}
}
MultiValueParamClass.prototype.PollingCallback = PollingCallback;
/*****************************************************************************/
function GetObjectPosition(obj) {
var totalTop = 0;
var totalLeft = 0;
while (obj != document.body) {
// Add up the position
totalTop += obj.offsetTop;
totalLeft += obj.offsetLeft;
// Prepare for next iteration
obj = obj.offsetParent;
}
totalTop += obj.offsetTop;
totalLeft += obj.offsetLeft;
return { Left: totalLeft, Top: totalTop };
}
function GetValueStringFromTextEditor(floatingEditorID, asRaw, allowBlank) {
var span = GetControl(floatingEditorID);
var editor = span.childNodes[0];
var valueString = editor.value;
// Remove the blanks
if (!allowBlank) {
// Break down the text box string to the individual lines
var valueArray = valueString.split("\r\n");
var delimiter;
if (asRaw)
delimiter = "\r\n";
else
delimiter = ", ";
var finalValue = "";
for (var i = 0; i < valueArray.length; i++) {
// If the string is non-blank, add it
if (valueArray[i].length > 0) {
if (finalValue.length > 0)
finalValue += delimiter;
finalValue += valueArray[i];
}
}
return finalValue;
}
else {
if (asRaw)
return valueString;
else
return valueString.replace(/\r\n/g, ", ");
}
}
function GetValueStringFromValidValueList(editorID) {
var valueString = "";
// Get the table
var div = GetControl(editorID);
var table = div.childNodes[0];
if (table.nodeName != "TABLE") // Skip whitespace if needed
table = div.childNodes[1];
// If there is only one element, it is a real value, not the select all option
var startIndex = 0;
if (table.rows.length > 1)
startIndex = 1;
for (var i = startIndex; i < table.rows.length; i++)
{
// Get the first cell of the row
var firstCell = table.rows[i].cells[0];
var span = firstCell.childNodes[0];
var checkBox = span.childNodes[0];
var label = span.childNodes[1];
if (checkBox.checked) {
if (valueString.length > 0)
valueString += ", ";
// chris edit - valueString += label.firstChild.nodeValue;
valueString += firstChildNoWS(label).nodeValue;
}
}
return valueString;
}
function MultiValidValuesSelectAll(src, editorID)
{
// Get the table
var div = GetControl(editorID);
var table = div.childNodes[0];
if (table.nodeName != "TABLE")
table = div.childNodes[1];
for (var i = 1; i < table.rows.length; i++)
{
// Get the first cell of the row
var firstCell = table.rows[i].cells[0];
var span = firstCell.childNodes[0];
var checkBox = span.childNodes[0];
checkBox.checked = src.checked;
}
}
function ValidateMultiValidValue(editorID, errMsg)
{
var summaryString = GetValueStringFromValidValueList(editorID);
var isValid = summaryString.length > 0;
if (!isValid)
alert(errMsg)
return isValid;
}
function ValidateMultiEditValue(editorID, errMsg) {
// Need to check for a value specified. This code only runs if not allow blank.
// GetValueStringFromTextEditor filters out blank strings. So if it was all blank,
// the final string will be length 0
var summaryString = GetValueStringFromTextEditor(editorID, true, false)
var isValid = false;
if (summaryString.length > 0)
isValid = true;
if (!isValid)
alert(errMsg);
return isValid;
}
function GetControl(controlID) {
var control = document.getElementById(controlID);
if (control == null)
alert("Unable to locate control: " + controlID);
return control;
}
function ControlClicked(formID) {
var form = GetControl(formID);
if (form.ActiveMultiValue != null)
form.ActiveMultiValue.Hide();
}
Part 2 of updated ReportingServices.js from my answer:
// --- Context Menu ---
// This function is called in the onload event of the body.
// It hooks the context menus up to the Javascript code.
// divContextMenuId, is the id of the div that contains the context menus
// selectedIdHiddenFieldId, is the id of the field used to post back the name of the item clicked
// contextMenusIds, is an array of the ids of the context menus
// searchTextBox ID, is the id of the search box
// defaultSearchValue. the value the search box has by default
function InitContextMenu(divContextMenuId, selectedIdHiddenFieldId, contextMenusIds, searchTextBoxID, defaultSearchValue ) {
ResetSearchBar( searchTextBoxID, defaultSearchValue );
_divContextMenu = document.getElementById(divContextMenuId);
_selectedIdHiddenField = document.getElementById(selectedIdHiddenFieldId);
_contextMenusIds = contextMenusIds;
_divContextMenu.onmouseover = function() { _mouseOverContext = true; };
_divContextMenu.onmouseout = function() {
if (_mouseOverContext == true) {
_mouseOverContext = false;
if (_timeOutTimer == null) {
_timeOutTimer = setTimeout(TimeOutAction, _timeOutLimit);
}
}
};
document.body.onmousedown = ContextMouseDown;
AddKeyDownListener();
}
// This handler stops bubling when arrow keys Up or Down pressed to prevent scrolling window
function KeyDownHandler(e)
{
// Cancel window scrolling only when menu is opened
if(_currentContextMenuId == null)
{
return true;
}
if(!e)
{
e = window.event;
}
var key = e.keyCode;
if(key == 38 || key == 40)
{
return false;
}
else
{
return true;
}
}
function AddKeyDownListener()
{
if(document.addEventListener)
{
document.addEventListener('keydown', KeyDownHandler, false);
}
else
{
document.onkeydown = KeyDownHandler;
}
}
// This function starts the context menu timeout process
function TimeOutAction() {
if (_mouseOverContext == false) {
UnSelectedMenuItem()
}
_timeOutTimer = null;
}
// This function is called when a name tag is clicked, it displays the contextmenu for a given item.
function Clicked(event, contextMenuId) {
if (!_onLink) {
ClearTimeouts();
SelectContextMenuFromColletion(contextMenuId);
_itemSelected = true;
// **Cross browser compatibility code**
// Some browsers will not pass the event so we need to get it from the window instead.
if (event == null)
event = window.event;
var selectedElement = event.target != null ? event.target : event.srcElement;
var outerTableElement = GetOuterElementOfType(selectedElement, 'table');
var elementPosition = GetElementPosition(outerTableElement);
_selectedItemId = outerTableElement.id;
// chris edit - _selectedIdHiddenField.value = outerTableElement.value;
_selectedIdHiddenField.value = outerTableElement.attributes["value"].value;
outerTableElement.className = "msrs-SelectedItem";
ResetContextMenu();
var contextMenuHeight = _divContextMenu.offsetHeight;
var contextMenuWidth = _divContextMenu.offsetWidth;
var boxHeight = outerTableElement.offsetHeight;
var boxWidth = outerTableElement.offsetWidth;
var boxXcoordinate = elementPosition.left;
var boxYcooridnate = elementPosition.top;
var pageWidth = 0, pageHeight = 0;
// **Cross browser compatibility code**
if (typeof (window.innerWidth) == 'number') {
//Non-IE
pageWidth = window.innerWidth;
pageHeight = window.innerHeight;
} else if (document.documentElement && (document.documentElement.clientWidth || document.documentElement.clientHeight)) {
//IE 6+ in 'standards compliant mode'
pageWidth = document.documentElement.clientWidth;
pageHeight = document.documentElement.clientHeight;
} else if (document.body && (document.body.clientWidth || document.body.clientHeight)) {
//IE 4 compatible
pageWidth = document.body.clientWidth;
pageHeight = document.body.clientHeight;
}
// **Cross browser compatibility code**
var iebody = (document.compatMode && document.compatMode != "BackCompat") ? document.documentElement : document.body
var pageXOffSet = document.all ? iebody.scrollLeft : pageXOffset
var pageYOffSet = document.all ? iebody.scrollTop : pageYOffset
_divContextMenu.style.left = SetContextMenuHorizonatalPosition(pageWidth, pageXOffSet, boxXcoordinate, contextMenuWidth, boxWidth) + 'px';
_divContextMenu.style.top = SetContextMenuVerticalPosition(pageHeight, pageYOffSet, boxYcooridnate, contextMenuHeight, boxHeight) + 'px';
ChangeOpacityForElement(100, _divContextMenu.id);
// chris edit - document.getElementById(_currentContextMenuId).firstChild.focus();
firstChildNoWS(document.getElementById(_currentContextMenuId)).focus();
}
}
// ***********************************
// Context menu keyboard navigation
// ***********************************
// Opens context menu via keyboard. Context menu
// is opened by selecting an item and pressing
// Alt + Down.
function OpenMenuKeyPress(e, contextMenuId)
{
// Alt key was pressed
if (e.altKey)
{
var keyCode;
if (window.event)
keyCode = e.keyCode;
else
keyCode = e.which;
// Down key was pressed
if (keyCode == 40)
{
// Open context menu.
Clicked(event, contextMenuId);
// Highlight the first selectable item
// in the context menu.
HighlightContextMenuItem(true);
}
}
}
// Performs keyboard navigation within
// opened context menu.
function NavigateMenuKeyPress(e)
{
var keyCode;
if (window.event)
keyCode = e.keyCode;
else
keyCode = e.which;
// Down key moves down to the next context menu item
if (keyCode == 40)
{
HighlightContextMenuItem(true);
}
// Up key moves up to the previous context menu item
else if (keyCode == 38)
{
HighlightContextMenuItem(false);
}
// Escape key closes context menu
else if (keyCode == 27)
{
// Close context menu
UnSelectedMenuItem();
// Make sure focus is given to the catalog item
// in the folder view.
document.getElementById(_selectedItemId).focus();
}
}
// Highlights context menu item.
// Parameter: highlightNext
// - If true, highlights menu item below current menu item.
// If current menu item is the last item, wraps around and
// highlights first menu item.
// - If false, highlights menu item above current menu item.
// If current menu item is the first item, wraps around and
// highlights last menu item.
function HighlightContextMenuItem(highlightNext)
{
var contextMenu = document.getElementById(_currentContextMenuId);
// chris edit - var table = contextMenu.lastChild;
var table = lastChildNoWS(contextMenu);
var currentMenuItemIndex = -1;
if (_currentMenuItemId != null)
currentMenuItemIndex = document.getElementById(_currentMenuItemId).parentNode.rowIndex;
var index = currentMenuItemIndex;
while (true)
{
if (highlightNext)
{
index++;
// If the index is out of range,
// reset it to the beginning
if (index < 0 || index >= table.cells.length)
index = 0;
}
else
{
index--;
// If the index is out of range,
// reset it to the end
if (index < 0 || index >= table.cells.length)
index = table.cells.length - 1;
}
// Each context menu item has an associated
// group ID. Make sure the table cell has a valid
// group ID, otherwise it is not a menu item (e.g.
// an underline separator).
if (table.cells[index].group >= 0)
{
FocusContextMenuItem(table.cells[index].id, 'msrs-MenuUIItemTableHover', 'msrs-MenuUIItemTableCell');
break;
}
// If we reach the orignal index, that means we looped
// through all table cells and did not find a valid context
// menu item. In that case, stop searching.
if (index == currentMenuItemIndex)
break;
}
}
// *** End keyboard navigation ***
// This function resets the context menus shape and size.
function ResetContextMenu() {
_divContextMenu.style.height = 'auto';
_divContextMenu.style.width = 'auto';
_divContextMenu.style.overflowY = 'visible';
_divContextMenu.style.overflowX = 'visible';
_divContextMenu.style.overflow = 'visible';
_divContextMenu.style.display = 'block';
}
// This function sets the horizontal position of the context menu.
// It also sets is the context menu has vertical scroll bars.
function SetContextMenuHorizonatalPosition(pageWidth, pageXOffSet, boxXcoordinate, contextMenuWidth, boxWidth) {
var menuXCoordinate = boxXcoordinate + boxWidth - contextMenuWidth;
var spaceRightBox = (pageWidth + pageXOffSet) - menuXCoordinate;
var spaceLeftBox = menuXCoordinate - pageXOffSet;
var returnValue;
if ((contextMenuWidth < spaceRightBox) && (pageXOffSet < menuXCoordinate)) {
returnValue = menuXCoordinate;
}
else if ((contextMenuWidth < spaceRightBox)) {
returnValue = pageXOffSet;
}
else if (contextMenuWidth < spaceLeftBox) {
returnValue = menuXCoordinate - (contextMenuWidth - (pageWidth + pageXOffSet - menuXCoordinate));
}
else {
_divContextMenu.style.overflowX = "scroll";
if (spaceLeftBox < spaceRightBox) {
_divContextMenu.style.width = spaceRightBox;
returnValue = pageXOffSet;
}
else {
_divContextMenu.style.width = spaceLeftBox;
returnValue = menuXCoordinate - (spaceLeftBox - (pageWidth + pageXOffSet - menuXCoordinate));
}
}
return returnValue;
}
// This function sets the vertical position of the context menu.
// It also sets is the context menu has horizontal scroll bars.
function SetContextMenuVerticalPosition(pageHeight, pageYOffSet, boxYcooridnate, contextMenuHeight, boxHeight) {
var spaceBelowBox = (pageHeight + pageYOffSet) - (boxYcooridnate + boxHeight);
var spaceAboveBox = boxYcooridnate - pageYOffSet;
var returnValue;
if (contextMenuHeight < spaceBelowBox) {
returnValue = (boxYcooridnate + boxHeight);
}
else if (contextMenuHeight < spaceAboveBox) {
returnValue = (boxYcooridnate - contextMenuHeight);
}
else if (spaceBelowBox > spaceAboveBox) {
_divContextMenu.style.height = spaceBelowBox;
_divContextMenu.style.overflowY = "scroll";
returnValue = (boxYcooridnate + boxHeight);
}
else {
_divContextMenu.style.height = spaceAboveBox;
_divContextMenu.style.overflowY = "scroll";
returnValue = (boxYcooridnate - spaceAboveBox);
}
return returnValue;
}
// This function displays a context menu given its id and then hides the others
function SelectContextMenuFromColletion(contextMenuConfigString) {
var contextMenuId = SplitContextMenuConfigString(contextMenuConfigString);
for (i = 0; i < _contextMenusIds.length; i++) {
var cm = document.getElementById(_contextMenusIds[i]);
if (cm.id == contextMenuId) {
cm.style.visibility = 'visible';
cm.style.display = 'block';
_currentContextMenuId = contextMenuId;
}
else {
cm.style.visibility = 'hidden';
cm.style.display = 'none';
}
}
}
function SplitContextMenuConfigString(contextMenuConfigString) {
var contextMenuEnd = contextMenuConfigString.indexOf(":");
var contextMenuId = contextMenuConfigString;
var contextMenuHiddenItems;
if (contextMenuEnd != -1)
{
contextMenuId = contextMenuConfigString.substr(0, contextMenuEnd);
}
var cm = document.getElementById(contextMenuId);
// chris edit - var table = cm.firstChild;
var table = firstChildNoWS(cm);
var groupItemCount = []; // The items in each group
var groupUnderlineId = []; // The Id's of the underlines.
// Enable all menu items counting the number of groups,
// number of items in the groups and underlines for the groups as we go.
// start chris edit
/* for (i = 0; i < table.cells.length; i++)
{
table.cells[i].style.visibility = 'visible';
table.cells[i].style.display = 'block'
if ((groupItemCount.length - 1) < table.cells[i].group) {
groupItemCount.push(1);
groupUnderlineId.push(table.cells[i].underline);
}
else {
groupItemCount[table.cells[i].group]++;
}
AlterVisibilityOfAssociatedUnderline(table.cells[i], true)
}*/
if (table != null && table.rows != null)
{
for (r = 0; r < table.rows.length; r++) {
for (i = 0; i < table.rows[r].cells.length; i++)
{
table.rows[r].cells[i].style.visibility = 'visible';
table.rows[r].cells[i].style.display = 'block'
if ((groupItemCount.length - 1) < table.rows[r].cells[i].group) {
groupItemCount.push(1);
groupUnderlineId.push(table.rows[r].cells[i].underline);
}
else {
groupItemCount[table.rows[r].cells[i].group]++;
}
AlterVisibilityOfAssociatedUnderline(table.rows[r].cells[i], true)
}
}
}
// end chris edit
// If hidden items are listed, remove them from the context menu
if (contextMenuEnd != -1)
{
contextMenuHiddenItems = contextMenuConfigString.substr((contextMenuEnd + 1), (contextMenuConfigString.length - 1)).split("-");
var groupsToHide = groupItemCount;
// Hide the hidden items
for (i = 0; i < contextMenuHiddenItems.length; i++)
{
var item = document.getElementById(contextMenuHiddenItems[i]);
item.style.visibility = 'hidden';
item.style.display = 'none'
groupsToHide[item.group]--;
}
var allHidden = true;
// Work back through the groups hiding the underlines as required.
for (i = (groupsToHide.length - 1); i > -1; i--) {
if (groupsToHide[i] == 0) {
AlterVisibilityOfAssociatedUnderline(groupUnderlineId[i], false);
}
else if (allHidden && i == (groupsToHide.length - 1)) {
allHidden = false;
}
// If all the items have been hidden so far hide the last underline too.
else if (allHidden) {
allHidden = false;
AlterVisibilityOfAssociatedUnderline(groupUnderlineId[i], false);
}
}
}
return contextMenuId;
}
function AlterVisibilityOfAssociatedUnderline(underLineId, visibility) {
if (underLineId != null && underLineId != "") {
var underlineElement = document.getElementById(underLineId);
if (underlineElement != null) {
if (visibility) {
underlineElement.style.visibility = 'visible';
underlineElement.style.display = 'block'
}
else {
underlineElement.style.visibility = 'hidden';
underlineElement.style.display = 'none'
}
}
}
}
function ClearTimeouts() {
if (_fadeTimeouts != null) {
for (i = 0; i < _fadeTimeouts.length; i++) {
clearTimeout(_fadeTimeouts[i]);
}
}
_fadeTimeouts = [];
}
// This function chnages an elements opacity given its id.
function FadeOutElement(id, opacStart, opacEnd, millisec) {
ClearTimeouts();
//speed for each frame
var speed = Math.round(millisec / 100);
var timer = 0;
for (i = opacStart; i >= opacEnd; i--) {
_fadeTimeouts.push(setTimeout("ChangeOpacityForElement(" + i + ",'" + id + "')", (timer * speed)));
timer++;
}
}
// This function changes the opacity of an elemnent given it's id.
// Works across browsers for different browsers
function ChangeOpacityForElement(opacity, id) {
var object = document.getElementById(id).style;
if (opacity != 0) {
// **Cross browser compatibility code**
object.opacity = (opacity / 100);
object.MozOpacity = (opacity / 100);
object.KhtmlOpacity = (opacity / 100);
object.filter = "alpha(opacity=" + opacity + ")";
}
else {
object.display = 'none';
}
}
// This function is the click for the body of the document
function ContextMouseDown() {
if (_mouseOverContext) {
return;
}
else {
HideMenu()
}
}
// This function fades out the context menu and then unselects the associated name control
function UnSelectedMenuItem() {
if (_itemSelected) {
FadeOutElement(_divContextMenu.id, 100, 0, 300);
UnselectCurrentMenuItem();
}
}
// Hides context menu without fading effect
function HideMenu()
{
if (_itemSelected)
{
ChangeOpacityForElement(0, _divContextMenu.id);
UnselectCurrentMenuItem();
}
}
function UnselectCurrentMenuItem()
{
_itemSelected = false;
_currentContextMenuId = null;
SwapStyle(_currentMenuItemId, 'msrs-MenuUIItemTableCell');
_currentMenuItemId = null;
ChangeReportItemStyle(_selectedItemId, "msrs-UnSelectedItem");
}
// This function walks back up the DOM tree until it finds the first occurrence
// of a given element. It then returns this element
function GetOuterElementOfType(element, type) {
while (element.tagName.toLowerCase() != type) {
element = element.parentNode;
}
return element;
}
// This function gets the corrdinates of the top left corner of a given element
function GetElementPosition(element) {
element = GetOuterElementOfType(element, 'table');
var left, top;
left = top = 0;
if (element.offsetParent) {
do {
left += element.offsetLeft;
top += element.offsetTop;
} while (element = element.offsetParent);
}
return { left: left, top: top };
}
function FocusContextMenuItem(menuItemId, focusStyle, blurStyle)
{
SwapStyle(_currentMenuItemId, blurStyle);
SwapStyle(menuItemId, focusStyle);
// chrid edit - document.getElementById(menuItemId).firstChild.focus();
firstChildNoWS(document.getElementById(menuItemId)).focus();
_currentMenuItemId = menuItemId;
}
// This function swaps the style using the id of a given element
function SwapStyle(id, style) {
if (document.getElementById) {
var selectedElement = document.getElementById(id);
if (selectedElement != null)
{
selectedElement.className = style;
}
}
}
// This function changes the style using the id of a given element
// and should only be called for catalog items in the tile or details view
function ChangeReportItemStyle(id, style)
{
if (!_itemSelected)
{
if (document.getElementById)
{
var selectedElement = document.getElementById(id);
selectedElement.className = style;
// Change the style on the end cell by drilling into the table.
if (selectedElement.tagName.toLowerCase() == "table")
{
// chris edit - var tbody = selectedElement.lastChild;
var tbody = lastChildNoWS(selectedElement);
if (tbody != null)
{
// chris edit - var tr = tbody.lastChild;
var tr = lastChildNoWS(tbody);
if (tr != null)
{
// chris edit - tr.lastChild.className = style + 'End';
trLastChild = lastChildNoWS(tr);
if (trLastChild != null)
{
trLastChild.className = style + 'End';
}
}
}
}
}
}
}
function ChangeReportItemStyleOnFocus(id, currentStyle, unselectedStyle)
{
_unselectedItemStyle = unselectedStyle;
_tabFocusedItem = id;
// We should unselect selected by mouse over item if there is one
if(_mouseOverItem != '')
{
ChangeReportItemStyle(_mouseOverItem, _unselectedItemStyle);
_mouseOverItem = '';
}
ChangeReportItemStyle(id, currentStyle);
}
function ChangeReportItemStyleOnBlur(id, style)
{
ChangeReportItemStyle(id, style);
_tabFocusedItem = '';
}
function ChangeReportItemStyleOnMouseOver(id, currentStyle, unselectedStyle)
{
_unselectedItemStyle = unselectedStyle;
_mouseOverItem = id;
// We should unselect tabbed item if there is one
if(_tabFocusedItem != '')
{
ChangeReportItemStyle(_tabFocusedItem, _unselectedItemStyle);
_tabFocusedItem = '';
}
ChangeReportItemStyle(id, currentStyle);
}
function ChangeReportItemStyleOnMouseOut(id, style)
{
ChangeReportItemStyle(id, style);
_mouseOverItem = '';
}
// This function is used to set the style of the search bar on the onclick event.
function SearchBarClicked(id, defaultText, style) {
var selectedElement = document.getElementById(id);
if (selectedElement.value == defaultText) {
selectedElement.value = "";
selectedElement.className = style;
}
}
// This function is used to set the style of the search bar on the onblur event.
function SearchBarBlured(id, defaultText, style) {
var selectedElement = document.getElementById(id);
if (selectedElement.value == "") {
selectedElement.value = defaultText;
selectedElement.className = style;
}
}
function ResetSearchBar(searchTextBoxID,defaultSearchValue) {
var selectedElement = document.getElementById(searchTextBoxID);
if (selectedElement != null) {
if (selectedElement.value == defaultSearchValue) {
selectedElement.className = 'msrs-searchDefaultFont';
}
else {
selectedElement.className = 'msrs-searchBarNoBorder';
}
}
}
function OnLink()
{
_onLink = true;
}
function OffLink()
{
_onLink = false;
}
function ShouldDelete(confirmMessage) {
if (_selectedIdHiddenField.value != null || _selectedIdHiddenField.value != "") {
var message = confirmMessage.replace("{0}", _selectedIdHiddenField.value);
var result = confirm(message);
if (result == true) {
return true;
}
else {
return false;
}
}
else {
return false;
}
}
function UpdateValidationButtonState(promptCredsRdoBtnId, typesDropDownId, forbiddenTypesConfigString, validateButtonId)
{
var dropdown = document.getElementById(typesDropDownId);
if(dropdown == null)
{
return;
}
var selectedValue = dropdown.options[dropdown.selectedIndex].value;
var forbiddenTypes = forbiddenTypesConfigString.split(":");
var chosenForbiddenType = false;
for (i = 0; i < forbiddenTypes.length; i++)
{
if(forbiddenTypes[i] == selectedValue)
{
chosenForbiddenType = true;
}
}
var isDisabled = chosenForbiddenType || IsRadioButtonChecked(promptCredsRdoBtnId);
ChangeDisabledButtonState(validateButtonId, isDisabled);
}
function ChangeDisabledButtonState(buttonId, isDisabled)
{
var button = document.getElementById(buttonId);
if(button != null)
{
button.disabled = isDisabled;
}
}
function IsRadioButtonChecked(radioButtonId)
{
var rbtn = document.getElementById(radioButtonId);
if(rbtn != null && rbtn.checked)
{
return true;
}
return false;
}