Autocompleter Javascript-for Wordpress site - javascript

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

Related

Other js function is ignoring my realtime calc function

I am at a lost here and have tried everything. My realtime calculation was being done into separate js file, but since I started using bootstrap template, it is not being executed. I have read through it and tried different thing but nothing is happening.
Php for calling realtime calc
<!-- ======================== PHONE INSURANCE ======================== -->
<select name="insurance" id='insurance' onChange="portInDatabase();">
<option disabled >Select Insurance</option>
<option value="None">None</option>
<option value="7">Yes</option>
</select><br>
<!-- ======================== PHONE CASE ======================== -->
<select name="case" id='case' onChange="portInDatabase()" onclick='portInDatabase()'>
<option disabled >Select Phone Case</option>
<option value="None">None</option>
<option value="25">Regular</option>
<option value="30">Wallet</option>
</select><br>
<!-- ======================== SCREEN PROTECTOR ======================== -->
<select name="screen" id='screen' onChange="portInDatabase();">
<option disabled >Select Screen Protector</option>
<option value="None">No</option>
<option value="15">Yes</option>
</select><br>
<!-- ======================== TOTAL FROM JS ======================== -->
<div id='total'></div>
Js for Real time calc(sorry for the long code)
// Array for plan prices
var plan_prices = new Array();
plan_prices["None"]= 0;
plan_prices["35"]=35;
plan_prices["50"]=50;
plan_prices["60"]=60;
// Array for insurance where "None" is the id from the html and it is equivalent
// to value 0 and so on
var insurance_phone = new Array();
insurance_phone["None"]=0;
insurance_phone["7"]=7;
//Array for phone case for price calculation
var phone_case = new Array();
phone_case["None"]=0;
phone_case["25"] = 25;
phone_case["30"] = 30;
//Array for screen protector
var screen_protector = new Array();
screen_protector["None"]=0;
screen_protector["15"] = 15;
// function for getting the plan price from the dropList
function getPlanPrice() {
var planSelected = 0;
var selectForm= document.forms["device"];
var selectedDevice3=selectForm.elements["plan"];
planSelected = plan_prices[selectedDevice3.value];
return planSelected;
}// end getPlanPrice
// function for getting the price when it is selected in the html dropList. This
// selection will single out the price we need for calculation.
function getInsurancePrice() {
var insuranceSelected = 0;
var selectForm= document.forms["device"];
var selectedDevice4=selectForm.elements["insurance"];
insuranceSelected = insurance_phone[selectedDevice4.value];
return insuranceSelected;
}// end getInsurancePrice
// Get the price for the selected option in the dropList to calculate.
function getCasePrice() {
var caseSelected = 0;
var selectForm= document.forms["device"];
var selectedDevice5=selectForm.elements["case"];
caseSelected = phone_case[selectedDevice5.value];
return caseSelected;
}// getCasePrice
// function to get the price for the screen.
function getScreenPrice() {
var screenSelected = 0;
var selectForm= document.forms["device"];
var selectedDevice6=selectForm.elements["screen"];
screenSelected = screen_protector[selectedDevice6.value];
return screenSelected;
}// getScreenPrice
// This function splits the data in the database to calculate the price for the
// device when port in is selected or when upgrade is selected and then it also checks
// whether anything else is selected in the form and does the real time calculation and
// outputs the result.
function portInDatabase(){
console.log("PortInDatabase started..")
debugger;
var price1, price2, price3, price4, price5, price6 = 0;
var port = 0;
var newAct = 0;
var up = 0;
var down = 0;
var act= 25; //Activation fee
// if the selection is a number then execute this
if(!isNaN(getPlanPrice())){
price2= getPlanPrice();
}
if(!isNaN(getInsurancePrice())){
price3= getInsurancePrice();
}
if(!isNaN(getCasePrice())){
price4= getCasePrice();
}
if(!isNaN(getScreenPrice())){
price5= getScreenPrice();
}
// This if statement is executed when Port is selected in the dropList and then
// it splits the rows which is connected to the device accordingly and then checks
// whether any of the other dropLists are selected so it can then calulate them and output it.
debugger;
if (document.getElementById('myport').selected == true){
var selDev = document.getElementById('selectDevice').value;
var port = selDev.split('#')[4]; // number of row in the database
port= parseFloat(port) +parseFloat(selDev.split('#')[1]*0.092)+price2 + price3 + price4 +price5+act;
port = port.toFixed(2); // rounds the decimal to 2
debugger;
document.getElementById('total').innerHTML= "Your Total: " +port;
}//end if
// for new Activation selection
else if(document.getElementById('srp').selected == true){
var selDev = document.getElementById('selectDevice').value;
var newAct = selDev.split('#')[1];
newAct= parseFloat(newAct) +parseFloat(selDev.split('#')[1]*0.092)+price2 + price3 + price4 +price5+act;
newAct = newAct.toFixed(2);
document.getElementById('total').innerHTML= "Your Total: " +newAct;
}//elseif
//for upgrade selection
else if(document.getElementById('upgrade').selected == true){
var selDev = document.getElementById('selectDevice').value;
var up = selDev.split('#')[2];
up = parseFloat(up) +parseFloat(selDev.split('#')[1]*0.092)+price2 + price3 + price4 +price5+act;
up = up.toFixed(2);
document.getElementById('total').innerHTML= "Your Total: " +up;
}//2nd elseif
//for down selection
else if(document.getElementById('down').selected == true){
var selDev= document.getElementById('selectDevice').value;
var down= selDev.split('#')[6];
down = parseFloat(port) +parseFloat(selDev.split('#')[1]*0.092)+price2 + price3 + price4 +price5+act;
down = down.toFixed(2);
document.getElementsById('total').innerHTML= "Your Total: " +down;
}//end 3rd elseif
else{
return false;
}//end else
}// end portInDatabase
JS of styling that is preventing real time calc
var CuteSelect = CuteSelect || {};
FIRSTLOAD = true;
SOMETHINGOPEN = false;
CuteSelect.tools = {
canRun: function() {
var myNav = navigator.userAgent.toLowerCase();
var browser = (myNav.indexOf('msie') != -1) ? parseInt(myNav.split('msie')[1]) : false;
if(browser) {
return (browser > 8) ? true : false;
} else { return true; }
},
uniqid: function() {
var n= Math.floor(Math.random()*11);
var k = Math.floor(Math.random()* 1000000);
var m = String.fromCharCode(n)+k;
return m;
},
hideEverything: function() {
if(SOMETHINGOPEN) {
SOMETHINGOPEN = false;
targetThis = false;
var cells = document.getElementsByTagName('div');
for (var i = 0; i < cells.length; i++) {
if(cells[i].hasAttribute('data-cuteselect-options')) {
var parent = cells[i].parentNode;
cells[i].style.opacity = '0';
cells[i].style.display = 'none';
}
}
}
},
getStyle: function() {
var css = '';
var stylesheets = document.styleSheets;
var css = '';
for(s = 0; s < stylesheets.length; s++) {
var classes = stylesheets[s].rules || stylesheets[s].cssRules;
for (var x = 0; x < classes.length; x++) {
if(classes[x].selectorText != undefined) {
var selectPosition = classes[x].selectorText.indexOf('select');
var optionPosition = classes[x].selectorText.indexOf('option');
var selectChar = classes[x].selectorText.charAt(selectPosition - 1);
var optionChar = classes[x].selectorText.charAt(optionPosition - 1);
if(selectPosition >= 0 && optionPosition >= 0 && (selectChar == '' || selectChar == '}' || selectChar == ' ') && (optionChar == '' || optionChar == '}' || optionChar == ' ')) {
text = (classes[x].cssText) ? classes[x].cssText : classes[x].style.cssText;
css += text.replace(/\boption\b/g, '[data-cuteselect-value]').replace(/\bselect\b/g, '[data-cuteselect-item]');
continue;
}
if(selectPosition >= 0) {
var character = classes[x].selectorText.charAt(selectPosition - 1);
if(character == '' || character == '}' || character == ' ') {
text = (classes[x].cssText) ? classes[x].cssText : classes[x].style.cssText;
css += text.replace(/\bselect\b/g, '[data-cuteselect-item]');
}
}
if(optionPosition >= 0) {
var character = classes[x].selectorText.charAt(optionPosition - 1);
if(character == '' || character == '}' || character == ' ') {
text = (classes[x].cssText) ? classes[x].cssText : classes[x].style.cssText;
css += text.replace(/\boption\b/g, '[data-cuteselect-value]');
}
}
}
}
}
return css;
},
createSelect: function(item) {
// Create custom select
var node = document.createElement("div");
if(item.hasAttribute('id')) { // Catch ID
node.setAttribute('id', item.getAttribute('id'));
item.removeAttribute('id');
}
if(item.hasAttribute('class')) { // Catch Class
node.setAttribute('class', item.getAttribute('class'));
item.removeAttribute('class');
}
// Hide select
item.style.display = 'none';
// Get Default value (caption)
var caption = null;
var cells = item.getElementsByTagName('option');
for (var i = 0; i < cells.length; i++) {
caption = cells[0].innerHTML;
if(cells[i].hasAttribute('selected')) {
caption = cells[i].innerHTML;
break;
}
}
// Get select options
var options = '<div data-cuteselect-title>' + caption + '</div><div data-cuteselect-options><div data-cuteselect-options-container>';
var cells = item.getElementsByTagName('option');
for (var i = 0; i < cells.length; i++) {
if(cells[i].hasAttribute('disabled')) { continue; }
if(cells[i].hasAttribute('class')) { var optionStyle = ' class="' + cells[i].getAttribute('class') + '"'; } else { var optionStyle = ''; }
if(cells[i].hasAttribute('id')) { var optionId = ' id="' + cells[i].getAttribute('id') + '"'; } else { var optionId = ''; }
if(cells[i].hasAttribute('selected')) { options += '<div data-cuteselect-value="' + cells[i].value + '" data-cuteselect-selected="true"' + optionStyle + optionId + '>' + cells[i].innerHTML + '</div>'; }
else { options += '<div data-cuteselect-value="' + cells[i].value + '"' + optionStyle + optionId + '>' + cells[i].innerHTML + '</div>'; }
}
options += '</div></div>';
// New select customization
node.innerHTML = caption;
node.setAttribute('data-cuteselect-item', CuteSelect.tools.uniqid());
node.innerHTML = options; // Display options
item.setAttribute('data-cuteselect-target', node.getAttribute('data-cuteselect-item'));
item.parentNode.insertBefore(node, item.nextSibling);
// Hide all options
CuteSelect.tools.hideEverything();
},
//settings of the options, their position and all
show: function(item) {
if(item.parentNode.hasAttribute('data-cuteselect-item')) { var source = item.parentNode.getAttribute('data-cuteselect-item'); }
else { var source = item.getAttribute('data-cuteselect-item'); }
var cells = document.getElementsByTagName('select');
if(item.hasAttribute('data-cuteselect-title')) {
item = item.parentNode;
var cells = item.getElementsByTagName('div');
}
else { var cells = item.getElementsByTagName('div'); }
for (var i = 0; i < cells.length; i++) {
if(cells[i].hasAttribute('data-cuteselect-options')) {
targetItem = cells[i];
cells[i].style.display = 'block';
setTimeout(function() { targetItem.style.opacity = '1'; }, 10);
cells[i].style.position = 'absolute';
cells[i].style.left = item.offsetLeft + 'px';
cells[i].style.top = (item.offsetTop + item.offsetHeight) + 'px';
}
}
item.focus();
SOMETHINGOPEN = item.getAttribute('data-cuteselect-item');
},
selectOption: function(item) {
var label = item.innerHTML;
var value = item.getAttribute('data-cuteselect-value');
var parent = item.parentNode.parentNode.parentNode;
var target = parent.getAttribute('data-cuteselect-item');
var cells = parent.getElementsByTagName('div');
for (var i = 0; i < cells.length; i++) {
if(cells[i].hasAttribute('data-cuteselect-title')) { cells[i].innerHTML = label; }
}
// Real select
var cells = document.getElementsByTagName('select');
for (var i = 0; i < cells.length; i++) {
var source = cells[i].getAttribute('data-cuteselect-target');
if(source == target) { cells[i].value = value; }
}
//CuteSelect.tools.hideEverything();
},
writeStyles: function() {
toWrite = '<style type="text/css">' + CuteSelect.tools.getStyle() + ' [data-cuteselect-options] { opacity: 0; display: none; }</style>';
document.write(toWrite);
}
};
CuteSelect.event = {
parse: function() {
var cells = document.getElementsByTagName('select');
for (var i = 0; i < cells.length; i++) { CuteSelect.tools.createSelect(cells[i]); }
},
listen: function() {
document.onkeydown = function(evt) {
evt = evt || window.event;
if (evt.keyCode == 27) { CuteSelect.tools.hideEverything(); }
};
document.onclick = function(event) {
FIRSTLOAD = false;
if((!event.target.getAttribute('data-cuteselect-item') && !event.target.getAttribute('data-cuteselect-value') && !event.target.hasAttribute('data-cuteselect-title')) || ((event.target.hasAttribute('data-cuteselect-item') || event.target.hasAttribute('data-cuteselect-title')) && SOMETHINGOPEN)) {
CuteSelect.tools.hideEverything();
return;
}
//when selected the option dropdown list closes
var action = event.target;
if(event.target.getAttribute('data-cuteselect-value')) {
CuteSelect.tools.selectOption(action);
CuteSelect.tools.hideEverything();
}
else { CuteSelect.tools.show(action); }
return false;
}
},
manage: function() {
if(CuteSelect.tools.canRun()) { // IE Compatibility
CuteSelect.event.parse();
CuteSelect.event.listen();
CuteSelect.tools.writeStyles();
}
}
};
// document.onload(function() {
CuteSelect.event.manage();
// });
I did not want to post this long question, but I am lost and do not know what to do. Thanks and sorry.

How does Javascript evaluate the right parenthesis?

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.

What is the Easiest way to fix the Ajax conflict error?

In my website (http://urlsaf.com/m8) I already added one Ajax based rating system but this system is not working properly. When ever I rate it, It's reloaded the page. In my past this Ajax based rating system was rated successfully without reload the page using XMLHttpRequest. Below I will give my rating.js and behavior.js for your reference. Anyone please give the solution for my Ajax conflict error. Thanks in advance.
1.rating.js
var xmlhttp if (!xmlhttp && typeof XMLHttpRequest!='undefined') {
try {
xmlhttp = new XMLHttpRequest();
} catch (e) {
xmlhttp=false
}
}
function myXMLHttpRequest() {
var xmlhttplocal;
try {
xmlhttplocal= new ActiveXObject("Msxml2.XMLHTTP")
} catch (e) {
try {
xmlhttplocal= new ActiveXObject("Microsoft.XMLHTTP")
} catch (E) {
xmlhttplocal=false;
}
}
if (!xmlhttplocal && typeof XMLHttpRequest!='undefined') {
try {
var xmlhttplocal = new XMLHttpRequest();
} catch (e) {
var xmlhttplocal=false;
alert('couldn\'t create xmlhttp object');
}
}
return(xmlhttplocal);
}
function sndReq(vote,id_num,ip_num,units) {
var theUL = document.getElementById('unit_ul'+id_num); // the UL
// switch UL with a loading div
theUL.innerHTML = '<div class="loading"></div>';
xmlhttp.open('get', 'rpc.php?j='+vote+'&q='+id_num+'&t='+ip_num+'&c='+units);
xmlhttp.onreadystatechange = handleResponse;
xmlhttp.send(null);
}
function handleResponse() {
if(xmlhttp.readyState == 4){
if (xmlhttp.status == 200){
var response = xmlhttp.responseText;
var update = new Array();
if(response.indexOf('|') != -1) {
update = response.split('|');
changeText(update[0], update[1]);
}
}
}
}
function changeText( div2show, text ) {
// Detect Browser
var IE = (document.all) ? 1 : 0;
var DOM = 0;
if (parseInt(navigator.appVersion) >=5) {DOM=1};
// Grab the content from the requested "div" and show it in the "container"
if (DOM) {
var viewer = document.getElementById(div2show);
viewer.innerHTML = text;
} else if(IE) {
document.all[div2show].innerHTML = text;
}
}
/* =============================================================== */
var ratingAction = {
'a.rater' : function(element){
element.onclick = function(){
var parameterString = this.href.replace(/.*\?(.*)/, "$1"); // onclick="sndReq('j=1&q=2&t=127.0.0.1&c=5');
var parameterTokens = parameterString.split("&"); // onclick="sndReq('j=1,q=2,t=127.0.0.1,c=5');
var parameterList = new Array();
for (j = 0; j < parameterTokens.length; j++) {
var parameterName = parameterTokens[j].replace(/(.*)=.*/, "$1"); // j
var parameterValue = parameterTokens[j].replace(/.*=(.*)/, "$1"); // 1
parameterList[parameterName] = parameterValue;
}
var theratingID = parameterList['q'];
var theVote = parameterList['j'];
var theuserIP = parameterList['t'];
var theunits = parameterList['c'];
//for testing alert('sndReq('+theVote+','+theratingID+','+theuserIP+','+theunits+')'); return false;
sndReq(theVote,theratingID,theuserIP,theunits); return false;
}
}
};
Behaviour.register(ratingAction);
2.behavior.js
var Behaviour = {
list : new Array,
register : function(sheet){
Behaviour.list.push(sheet);
},
start : function(){
Behaviour.addLoadEvent(function(){
Behaviour.apply();
});
},
apply : function(){
for (h=0;sheet=Behaviour.list[h];h++){
for (selector in sheet){
list = document.getElementsBySelector(selector);
if (!list){
continue;
}
for (i=0;element=list[i];i++){
sheet[selector](element);
}
}
}
},
addLoadEvent : function(func){
var oldonload = window.onload;
if (typeof window.onload != 'function') {
window.onload = func;
} else {
window.onload = function() {
oldonload();
func();
}
}
}
}
Behaviour.start();
function getAllChildren(e) {
// Returns all children of element. Workaround required for IE5/Windows. Ugh.
return e.all ? e.all : e.getElementsByTagName('*');
}
document.getElementsBySelector = function(selector) {
// Attempt to fail gracefully in lesser browsers
if (!document.getElementsByTagName) {
return new Array();
}
// Split selector in to tokens
var tokens = selector.split(' ');
var currentContext = new Array(document);
for (var i = 0; i < tokens.length; i++) {
token = tokens[i].replace(/^\s+/,'').replace(/\s+$/,'');;
if (token.indexOf('#') > -1) {
// Token is an ID selector
var bits = token.split('#');
var tagName = bits[0];
var id = bits[1];
var element = document.getElementById(id);
if (tagName && element.nodeName.toLowerCase() != tagName) {
// tag with that ID not found, return false
return new Array();
}
// Set currentContext to contain just this element
currentContext = new Array(element);
continue; // Skip to next token
}
if (token.indexOf('.') > -1) {
// Token contains a class selector
var bits = token.split('.');
var tagName = bits[0];
var className = bits[1];
if (!tagName) {
tagName = '*';
}
// Get elements matching tag, filter them for class selector
var found = new Array;
var foundCount = 0;
for (var h = 0; h < currentContext.length; h++) {
var elements;
if (tagName == '*') {
elements = getAllChildren(currentContext[h]);
} else {
elements = currentContext[h].getElementsByTagName(tagName);
}
for (var j = 0; j < elements.length; j++) {
found[foundCount++] = elements[j];
}
}
currentContext = new Array;
var currentContextIndex = 0;
for (var k = 0; k < found.length; k++) {
if (found[k].className && found[k].className.match(new RegExp('\\b'+className+'\\b'))) {
currentContext[currentContextIndex++] = found[k];
}
}
continue; // Skip to next token
}
// Code to deal with attribute selectors
if (token.match(/^(\w*)\[(\w+)([=~\|\^\$\*]?)=?"?([^\]"]*)"?\]$/)) {
var tagName = RegExp.$1;
var attrName = RegExp.$2;
var attrOperator = RegExp.$3;
var attrValue = RegExp.$4;
if (!tagName) {
tagName = '*';
}
// Grab all of the tagName elements within current context
var found = new Array;
var foundCount = 0;
for (var h = 0; h < currentContext.length; h++) {
var elements;
if (tagName == '*') {
elements = getAllChildren(currentContext[h]);
} else {
elements = currentContext[h].getElementsByTagName(tagName);
}
for (var j = 0; j < elements.length; j++) {
found[foundCount++] = elements[j];
}
}
currentContext = new Array;
var currentContextIndex = 0;
var checkFunction; // This function will be used to filter the elements
switch (attrOperator) {
case '=': // Equality
checkFunction = function(e) { return (e.getAttribute(attrName) == attrValue); };
break;
case '~': // Match one of space seperated words
checkFunction = function(e) { return (e.getAttribute(attrName).match(new RegExp('\\b'+attrValue+'\\b'))); };
break;
case '|': // Match start with value followed by optional hyphen
checkFunction = function(e) { return (e.getAttribute(attrName).match(new RegExp('^'+attrValue+'-?'))); };
break;
case '^': // Match starts with value
checkFunction = function(e) { return (e.getAttribute(attrName).indexOf(attrValue) == 0); };
break;
case '$': // Match ends with value - fails with "Warning" in Opera 7
checkFunction = function(e) { return (e.getAttribute(attrName).lastIndexOf(attrValue) == e.getAttribute(attrName).length - attrValue.length); };
break;
case '*': // Match ends with value
checkFunction = function(e) { return (e.getAttribute(attrName).indexOf(attrValue) > -1); };
break;
default :
// Just test for existence of attribute
checkFunction = function(e) { return e.getAttribute(attrName); };
}
currentContext = new Array;
var currentContextIndex = 0;
for (var k = 0; k < found.length; k++) {
if (checkFunction(found[k])) {
currentContext[currentContextIndex++] = found[k];
}
}
// alert('Attribute Selector: '+tagName+' '+attrName+' '+attrOperator+' '+attrValue);
continue; // Skip to next token
}
if (!currentContext[0]){
return;
}
// If we get here, token is JUST an element (not a class or ID selector)
tagName = token;
var found = new Array;
var foundCount = 0;
for (var h = 0; h < currentContext.length; h++) {
var elements = currentContext[h].getElementsByTagName(tagName);
for (var j = 0; j < elements.length; j++) {
found[foundCount++] = elements[j];
}
}
currentContext = found;
}
return currentContext;
}
/* That revolting regular expression explained
/^(\w+)\[(\w+)([=~\|\^\$\*]?)=?"?([^\]"]*)"?\]$/
\---/ \---/\-------------/ \-------/
| | | |
| | | The value
| | ~,|,^,$,* or =
| Attribute
Tag
*/

SSRS Report Manager javascript fails in non-IE browsers for Drop Down Menus

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;
}

problem with google chrome

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/)

Categories

Resources