// Control multiple onload functions
function addOnload(fnc) {
	if(typeof fnc == "function") {
		if ( typeof window.addEventListener != "undefined") {
			window.addEventListener( "load", fnc, false );
		} else if ( typeof window.attachEvent != "undefined" ) {
				window.attachEvent( "onload", fnc );
		} else {
			if ( window.onload != null ) {
				var oldOnload = window.onload;
				window.onload = function () {
					oldOnload();
					window[fnc]();
				};
			} else {
				window.onload = fnc;
			}
		}
	}
}

// Get elements with a particular class name.
document.getElementsByClassName = function(cl) {
	var retnode = [];
	var myclass = new RegExp("\\b"+cl+"\\b");
	var elem = this.getElementsByTagName("*");
	for (var i = 0; i < elem.length; i++) {
		var classes = elem[i].className;
		if (myclass.test(classes)) {
			retnode.push(elem[i]);
		}
	}
	return retnode;
};

var ticketcount = 1;
var datecount = 1;
var imagecount = 1;
var iKeywordCount = 2;
function add_option(div) {
	var newdiv = document.createElement('div');
	switch (div) {
		case 'dates':
			datecount++;
            // Welcome to a nice and complicated block of javascript....
            // initiate some elements we're going to need to play with.
            
            var newrow = document.createElement('tr');
            var newcellblank = document.createElement('td');
            var newcellstart = document.createElement('td');
            var newcellend = document.createElement('td');
            newcellblank.style.textAlign = 'left';
            
            // Apply some styles where necessary.
            newcellblank.className = 'listing_field_title';

            newcellblank.innerHTML = '&nbsp;';            
            // Add some content to the content cells.
            newcellstart.innerHTML ="\n<input id='from_" + datecount + "' name='from_" + datecount + "' class='field short' onclick='displayDatePicker(\"from_" + datecount + "\");' value='' autocomplete='off' />";
            newcellend.innerHTML ="\n<input id='to_" + datecount + "' name='to_" + datecount + "' class='field short' onclick='displayDatePicker(\"to_" + datecount + "\");' value='' autocomplete='off' />";

            // Add the rows first, then append the cells as children to the rows.
            document.getElementById('dates_info').appendChild(newrow);
            newrow.appendChild(newcellblank);
            newrow.appendChild(newcellstart);
            newrow.appendChild(newcellend);
			break;
		case 'tickets':
			ticketcount++;
             // Welcome to a nice and complicated block of javascript....
            // initiate some elements we're going to need to play with.
            
            var newrow = document.createElement('tr');
            var newcellblank = document.createElement('td');
            var newcellstart = document.createElement('td');
            var newcellend = document.createElement('td');
            newcellblank.style.textAlign = 'left';
            
            // Apply some styles where necessary.
            newcellblank.className = 'listing_field_title';

            newcellblank.innerHTML = '&nbsp;';            
            // Add some content to the content cells.
            newcellstart.innerHTML ="\n<input id='type_" + ticketcount + "' name='type_" + ticketcount + "' class='field short' value='' />";
            newcellend.innerHTML ="\n<input id='amount_" + ticketcount + "' name='amount_" + ticketcount + "' class='field short' value='' />";

            // Add the rows first, then append the cells as children to the rows.
            document.getElementById('tickets_info').appendChild(newrow);
            newrow.appendChild(newcellblank);
            newrow.appendChild(newcellstart);
            newrow.appendChild(newcellend);           

			break;
		case 'images':
			imagecount++;
			//newdiv.innerHTML = "<br /><label for='image"+imagecount+"'>New Image "+imagecount+":</label>\n<input type='file' name='image"+imagecount+"'>\n"
			//	+"<label for='image"+imagecount+"alt'>Description:</label>\n<input type='text' name='image"+imagecount+"alt'>\n"
			//	+"<label for='image"+imagecount+"title'>Title:</label>\n<input type='text' name='image"+imagecount+"title'>\n";
            var newrow = document.createElement('tr');
            var newcellimage = document.createElement('td');
            var newcellalt = document.createElement('td');
            var newcelltitle = document.createElement('td');
            
                   strSomething = "<tr>"
                    +"<td><input type='file' name='image"+imagecount+"'></td>"
                    +"<td></td>"
                    +"<td><input type='text' name='image"+imagecount+"title'></td>"
                    "</tr>";

            newcellimage.innerHTML = "<input type='file' name='image"+imagecount+"'>";
            newcellalt.innerHTML = "<input type='text' name='image"+imagecount+"alt'>";
            newcelltitle.innerHTML = "<input type='text' name='image"+imagecount+"title'>";

			document.getElementById('image_table').appendChild(newrow);
            newrow.appendChild(newcellimage);
            newrow.appendChild(newcellalt);
            newrow.appendChild(newcelltitle);
			break;
        case 'keyword':
            if(iKeywordCount < 10) {
              
              newdiv.style.padding = '3px';
              iKeywordCount++;
              newdiv.innerHTML = iKeywordCount+".<input type='text' class='filterTextActive' name='keyword"+iKeywordCount+"' value='' style='width: 225px;' />";
              document.getElementById('keywords_list').appendChild(newdiv);
            } 
            
            if(iKeywordCount == 10) {
              document.getElementById('keywordLink').style.display = 'none';
            }
            break;
	}
}

function print_r( array, return_val ) {
    // http://kevin.vanzonneveld.net
    // +   original by: Michael White (http://getsprink.com)
    // +   improved by: Ben Bryan
    // +      input by: Brett Zamir
    // +   improved by: Kevin van Zonneveld (http://kevin.vanzonneveld.net)
    // *     example 1: print_r(1, true);
    // *     returns 1: 1
    
    var output = "", pad_char = " ", pad_val = 4;
 
    var formatArray = function (obj, cur_depth, pad_val, pad_char) {
        if (cur_depth > 0) {
            cur_depth++;
        }
 
        var base_pad = repeat_char(pad_val*cur_depth, pad_char);
        var thick_pad = repeat_char(pad_val*(cur_depth+1), pad_char);
        var str = "";
 
        if (obj instanceof Array || obj instanceof Object) {
            str += "Array\n" + base_pad + "(\n";
            for (var key in obj) {
                if (obj[key] instanceof Array) {
                    str += thick_pad + "["+key+"] => "+formatArray(obj[key], cur_depth+1, pad_val, pad_char);
                } else {
                    str += thick_pad + "["+key+"] => " + obj[key] + "\n";
                }
            }
            str += base_pad + ")\n";
        } else if(obj == null || obj == undefined) {
            str = '';
        } else {
            str = obj.toString();
        }
 
        return str;
    };
 
    var repeat_char = function (len, pad_char) {
        var str = "";
        for(var i=0; i < len; i++) { 
            str += pad_char; 
        }
        return str;
    };
    output = formatArray(array, 0, pad_val, pad_char);
 
    if (return_val !== true) {
        document.write("<pre>" + output + "</pre>");
        return true;
    } else {
        return output;
    }
}

function alert_r() {
        var alerts = new Array();
        for (var i = 0; i < arguments.length; i++) {
                alerts.push(print_r(arguments[i],true).replace(/ /g,String.fromCharCode(160)));
        }
        alert(alerts.join('\n'));
}


/*
  Google search functions
    Added by Rob Terry, 9th Dec 2009.
*/


var globalSearch;
var searchFunction = function() {
  // Does the search for the element name return any results?
  eSearch = document.getElementsByName('search');
  // If our search returned some results, then...
  if(eSearch.length > 0) {
    // We should be able to work with the result field.
    if(eSearch.item(0).name == 'search') {
        // set the globalSearch variable.
        globalSearch = eSearch.item(0);
    }
  } else {
    // Otherwise we'll have to do it the old fashioned way!
    eInput = document.getElementsByTagName('input');

    // Loop the tagname results and search for the one with the search name.
    for(var i = 0; i < eInput.length; i++)
    {
      // Grab the item and set a variable to the object for the duration of the loop.
      var obj = eInput.item(i);
      
      // If the object we're currently viewing has the name set to search, then that's
      // the object we're looking for. It's the search input field.
      if(obj.name == 'search') {
        // Set the globalSearch variable to being the object we're looking at now, so we
        // can do some stuff with it later on!
        globalSearch = obj;
      }
    }
  }

  // Finally, we need to add a listener for the clicking of the clear button.
  eClearTD = document.getElementsByTagName('td');
  for(var i = 0; i < eClearTD.length; i++) {
    // Set the object to the search result.
    var obj = eClearTD.item(i);
    
    // If the objects class name is the same as the clear button class, then we are
    // looking at the right table cell.
    if(obj.className == 'gsc-clear-button')
    {
      // Attach the onclick event.
      AttachEvent(obj, 'click',searchClear);
    }
  }

  // Finally, we need to add a listener for the clicking of the clear button.
  eSearchButton = document.getElementsByTagName('input');
  for(var i = 0; i < eSearchButton.length; i++) {
    // Set the object to the search result.
    var obj = eSearchButton.item(i);
    
    // If the objects class name is the same as the clear button class, then we are
    // looking at the right table cell.
    if(obj.className == 'gsc-search-button' && obj.value == 'Search')
    {
      // Attach the onclick event.
      AttachEvent(obj, 'click',searchSubmit);
    }
  }
}

// AttachEvent()
// Params:
//  el          - Element we're attaching the event to.
//  event       - Type of event to attach.
//  myFunction  - Function name without parenthesis.
// Returns:
//  Attaches the required function to the object for the given event.
// Revisions:
//  Created by Rob Terry, 9th Dec 2009.
function AttachEvent(el, event, myFunction){
  if( el.addEventListener ) {
    el.addEventListener(event,myFunction,false);
  } else if( el.attachEvent ) {
    el.attachEvent('on'+event,myFunction);
  }
} 

// searchClear()
// Params:
//  None.
// Returns:
//  Set's the search div to dissapear.
// Revisions:
//  Created by Rob Terry, 9th Dec 2009.
function searchSubmit() {
  // Does the search field have any content?
  if(globalSearch.value == '') {
    // If so, then set the boolean to false, so the search div will dissapear.
    b = false;
  } else {
    // Otherwise, it needs to be displayed.
    b = true;
  } 
  searchDivDisplay(b);
}


// searchClear()
// Params:
//  None.
// Returns:
//  Set's the search div to dissapear.
// Revisions:
//  Created by Rob Terry, 9th Dec 2009.
function searchClear() {
  // Set the div to dissapear.
  searchDivDisplay(false);
}

// searchDivDisplay()
// Params:
//  bDisplay [BOOL] -   TRUE if the search div should be displayed.
//                      FALSE if otherwise.
// Returns:
//  Show's or Hides the search div, dependant on the boolean value passed.
// Revisions:
//  Created by Rob Terry, 9th Dec 2009.
function searchDivDisplay(bDisplay) {

  // Grab the search content div.
  searchContent = document.getElementById('searchDiv');
  
  // If display is set to TRUE
  if(bDisplay == true)
  {
    // Show the search results and hide the other columns.
    searchContent.style.display = 'block';
    document.getElementById('column_1').style.display = 'none';
    document.getElementById('column_2').style.display = 'none';
    document.getElementById('homeDiv').style.display = 'none';
  } else {
    // Otherwise, hide the search div and display the original content.
    searchContent.style.display = 'none';
    document.getElementById('column_1').style.display = 'block';
    document.getElementById('column_2').style.display = 'block';
    document.getElementById('homeDiv').style.display = 'block';
  }
}

function swapBookingImage(id, url) {
  document.getElementById(id+'_image').src = url;
}

/*
  add listings javascript
*/

function startSearch() {
  document.getElementById('searchingDiv').style.display = 'inline';
}

function showLocationChange(ele) {
  ele.innerHTML = '';
  input = document.createElement('input');
  input.type = 'text';
  input.name = 'location';
  input.id = 'location';
  input.className = 'suggestTextActive';
  ele.appendChild(input);
  setAutoSuggesField('location',{script:'/_ajax/autosuggest.php?',fldtype:'location',fldrturn:'locaid',postJsCMD:"storeLocationChange(document.getElementById('"+ele.id+"'), 'location');", linked:"false",dtxt:'e.g. Cardiff',dtxt_dstyle:'suggestText',dtxt_astyle:'suggestTextActive'},{exclusiveSearch:'loca'});
  input.value = '';
  input.className = 'suggestTextActive';
  input.focus();
}

function storeLocationChange(location) {
  value = document.getElementById(location).value;
  kjax('setSession',{userDefinedLocation: document.getElementById('locaid').value+'###'+value},'fail','fail');
}


var tempHandle = function(e) { showDistanceSlider(this) };

function loadRadiusSlider() {
  document.getElementById('distance').addEventListener('click', tempHandle, false);
}

function showDistanceSlider(ele) {
  
  div = document.createElement('div');
  div.id = 'radiusSliderContainer';
  div.style.position = 'absolute';
  div.style.backgroundColor = '#ccffff';
  div.style.padding = '2px';

  getPos = function(ele){
      var e = this.d_gE(ele);
      var obj = ele;
      var curleft = 0;
      if (obj.offsetParent){
          while (obj.offsetParent){
              curleft += obj.offsetLeft;
              obj = obj.offsetParent;
          }
      }
      else if (obj.x) curleft += obj.x;
      var obj = ele;
      var curtop = 0;
      if (obj.offsetParent){
          while (obj.offsetParent){
              curtop += obj.offsetTop;
              obj = obj.offsetParent;
          }
      }
      else if (obj.y) curtop += obj.y;
      return {x:curleft, y:curtop};
  };
  
  slider = document.createElement('div');
  slider.setAttribute('class', 'radiusSlider');
  slider.setAttribute('className', 'radiusSlider');
  slider.style.display = 'block';
  slider.style.clear = 'none';
  slider.style.float = 'right';
  slider.setAttribute('id','radiusSlider');
  sliderInput = document.createElement('input');
  sliderInput.setAttribute('class', 'radiusSlider-input');
  sliderInput.setAttribute('className', 'radiusSlider-input');
  sliderInput.setAttribute('id', 'radiusSlider-input');
  sliderInput.setAttribute('name', 'radiusSlider-input');
  sliderInput.setAttribute('tabindex', '1');
  slider.appendChild(sliderInput);
  div.appendChild(slider);
  
  pos = this.getPos(ele);
  
  div.style.top = pos.y+ele.offsetHeight+3+"px";
  document.getElementsByTagName('body')[0].appendChild(div);  
  
  document.getElementById('distance').removeEventListener('click',tempHandle,false);
  
  
  radiusSlider = new Slider(document.getElementById('radiusSlider'),document.getElementById('radiusSlider-input'), 'horizontal', '200px');
  radiusSlider.setValue(ele.value);
  radiusSlider.setMinimum(2);
  radiusSlider.setMaximum(50);
  radiusSlider.onchange = function() { sliderUpdate.value=radiusSlider.getValue();hideRadiusSlider(1500);  };
  var sliderUpdate = document.getElementById('distance');
  sliderUpdate.onchange = function () {radiusSlider.setValue(parseInt(this.value));};
  
  
  div.style.width = '200px';
  div.style.left = pos.x+(ele.offsetWidth-div.offsetWidth)+"px";
 
  hideRadiusSlider(1500);
}
hTemp = '';
function hideRadiusSlider(iTimeTillHide) {
  if(hTemp != '') { clearTimeout(hTemp); }
  hTemp = setTimeout("destroyRadiusSlider();",iTimeTillHide);
}

function destroyRadiusSlider() {
  radiusContainer = document.getElementById('radiusSliderContainer');
  radiusContainer.parentNode.removeChild(radiusContainer);
  loadRadiusSlider();
}


bAllChecked = 0;
function checkAll(fieldName, ele)
{
  field = document.getElementsByName(fieldName);
  for (i = 0; i < field.length; i++) field[i].checked = true ;
  ele.setAttribute('onclick',"checkNone('"+fieldName+"',this)");
  bAllChecked = 1;
}

function checkNone(fieldName, ele)
{
  field = document.getElementsByName(fieldName);
  for (i = 0; i < field.length; i++) field[i].checked = false ;
  ele.setAttribute('onclick',"checkAll('"+fieldName+"',this)");
  bAllChecked = 0;
}

function uncheckAllOption() {
  if(bAllChecked == 1) {
    document.getElementById('modules_all').checked = false;
    document.getElementById('modules_all').setAttribute('onclick',"checkAll('modules[]',this)");
  }
}

var aSites = new Array();
var aFranchise = new Array();
var aAdded = new Array();
function loadFranchiseSites(iFranchise,strIDs) {  
  if(in_array (iFranchise, aAdded)) return;
  aFranchise = new Array();
  aFranchisePairs = strIDs.split(",");
  
  for(i = 0; i < aFranchisePairs.length; i++) {
    aFranchise[i] = aFranchisePairs[i].split("=");
  }
  
  aSites[iFranchise] = new Array();
  aSites[iFranchise] = aFranchise;
  aAdded[iFranchise] = iFranchise;
}

function loadSiteDrop(strFranchiseDrop, strSiteDrop, iFranchise, iSite, bAll) {
  
  if(document.getElementById(strFranchiseDrop).value != iFranchise) { document.getElementById(strFranchiseDrop).value = iFranchise; }
  
  drop = document.getElementById(strSiteDrop);
  
  if(drop.hasChildNodes())  {
      while(drop.childNodes.length >= 1) { drop.removeChild( drop.firstChild ); } 
  }

  opt = document.createElement('option');
  opt.value = '';
  opt.innerHTML = 'Please choose';
  drop.appendChild(opt);


  if(typeof bAll != 'undefined' || iFranchise == 'all') {
    opt = document.createElement('option');
    opt.value = 'all';
    opt.innerHTML = 'All';
    drop.appendChild(opt);
    if(iFranchise == 'all') { drop.value = 'all'; return; }
  } 
  
  for(i = 0; i < aSites[iFranchise].length; i++) {
    opt = document.createElement('option');
    opt.value=aSites[iFranchise][i][0];
    opt.innerHTML = aSites[iFranchise][i][1];
    drop.appendChild(opt);
  }
  
  if(typeof iSite != 'undefined') { drop.value = iSite; }
}

function loadTrackingOntoAnchors(strBanner, strModule, iBanner) {
  trackBanner(iBanner, 'impression', strModule);
  div = document.getElementById(strBanner);
  convertAnchorTags(div, strModule, iBanner);
}

function convertAnchorTags(ele, strModule, iBanner) {
  var y = ele.getElementsByTagName("A"); 
  for (var i = 0; i < y.length; i++) { 
      newHref = "/exit.php?banner="+iBanner+"&type=click&bannerModule="+strModule+"&url="+escape(y[i].href).replace(/\//g,"%2F")
      y[i].href = newHref;
  }
}

function trackBanner(iBanner, strType, strModule) {
  kjax('trackBanner',{id:iBanner, type:strType, module:strModule},'fail','fail');
}

function fail(array) {
//  console.log(array);
}

function in_array (needle, haystack, argStrict) {
    var key = '', strict = !!argStrict;

    if (strict) {
        for (key in haystack) {
            if (haystack[key] === needle) {
                return true;
            }
        }
    } else {
        for (key in haystack) {
            if (haystack[key] == needle) {
                return true;
            }
        }
    }

    return false;
}

function changeTaskVisibility(strVisibility) {
  hide = (strVisibility == 'none'?'yes':'no');
  kjax('setSession',{hideTasks:hide},'fail','fail');
  
  taskHeaders = document.getElementsByClassName('headerRow');
  for(i = 0; i < taskHeaders.length; i++) {
    taskHeaders[i].style.display = strVisibility;
  }
  document.getElementById('adminSeparator').style.display = strVisibility;
  document.getElementById('hideLink').href = "javascript:changeTaskVisibility('"+(strVisibility == 'none'?'block':'none')+"');";
  document.getElementById('hideLink').innerHTML = (hide == 'yes'?'Show Tasks':'Hide Tasks');
}


var bSuccess = false;

function setReviewPage(reviewLink) {
  var bSuccess = false;
  linkParams = reviewLink.split("/");
  iBusiness = linkParams[7].substr(1);
  reviewLink = linkParams[8].split("#review");
  iPage = reviewLink[1];
  if(typeof iPage == 'null' || typeof iPage == 'undefined') iPage = 1;
  kjax('getReviews',{page:iPage, business:iBusiness, max:3, exitURL:reviewLink},'successReview','fail');  
}


function successReview(aReviews) {
  
  reviewList = document.getElementById('reviewListFull');
  if(reviewList.hasChildNodes())  {
      while(reviewList.childNodes.length >= 1) { reviewList.removeChild( reviewList.firstChild ); } 
  }
  
  reviewTopContent = document.getElementById('reviewTop');
  if(reviewTopContent.hasChildNodes() >= 1)  {
      while(reviewTopContent.childNodes.length >= 1) { reviewTopContent.removeChild( reviewTopContent.firstChild ); } 
  }
  
  // Review link.
  anchorlink = document.createElement('a');
  anchorlink.setAttribute('id', "review"+aReviews['page']);
  anchorlink.setAttribute('name', "review"+aReviews['page']);
  reviewTopContent.appendChild(anchorlink);
    
  for(var i in aReviews['reviews']) {
    // Review div.
    review = document.createElement('div');
    review.setAttribute('class','reviewList');
    review.setAttribute('className','reviewList');
    
    // left quote mark
    leftQuote = document.createElement('div');
    leftQuote.setAttribute('class','leftQuote');
    leftQuote.setAttribute('className','leftQuote');    
    
    // right quote mark
    rightQuote = document.createElement('div');
    rightQuote.setAttribute('class','rightQuote');
    rightQuote.setAttribute('className','rightQuote');
    
    // center content.
    reviewDiv = document.createElement('div');
    reviewDiv.setAttribute('class','reviewCenterField');
    reviewDiv.setAttribute('className','reviewCenterField');
    
    // review text.
    if(aReviews['reviews'][i]['reviewText'].length <= 300) {
      reviewText = document.createTextNode(aReviews['reviews'][i]['reviewText']);
      reviewDiv.appendChild(reviewText);
    } else {
      strBeforeCurtail = document.createTextNode(aReviews['reviews'][i]['reviewText'].substr(0,300));
      strAfterCurtail = document.createTextNode(aReviews['reviews'][i]['reviewText'].substr(300));
      moreLink = document.createElement('a');
      lessLink = document.createElement('a');
      moreLink.id = 'moreLink'+i;
      lessLink.id = 'lessLink'+i;
      moreLink.innerHTML = 'more...';
      lessLink.innerHTML = 'less';
      moreLink.href = '#';
      lessLink.href = '#';
      moreLink.onclick = function(){ return showMore(this); }
      lessLink.onclick = function(){ return showLess(this); }
      moreLink.style.display = 'inline';
      lessLink.style.display = 'none';
      moreLink.style.paddingLeft = '5px';
      lessLink.style.paddingLeft = '5px';
      beforeCurtail = document.createElement('div');
      beforeCurtail.setAttribute('id','beforeCurtail'+i);
      beforeCurtail.appendChild(strBeforeCurtail);
      beforeCurtail.style.display = 'inline';
      beforeCurtail.setAttribute('class','beforeCurtail');
      beforeCurtail.setAttribute('className','beforeCurtail');
      
      afterCurtail = document.createElement('div');
      afterCurtail.setAttribute('id','afterCurtail'+i);
      afterCurtail.appendChild(strAfterCurtail);
      afterCurtail.style.display = 'none';
      afterCurtail.setAttribute('class','afterCurtail');
      afterCurtail.setAttribute('className','afterCurtail');
      
      reviewDiv.appendChild(beforeCurtail);
      reviewDiv.appendChild(moreLink);
      reviewDiv.appendChild(afterCurtail);
      reviewDiv.appendChild(lessLink);
    }
        
    separator = document.createElement('div');
    separator.setAttribute('class','li_separator');
    separator.setAttribute('className','li_separator');
    separator.style.visibility = 'hidden';
    reviewDiv.appendChild(separator);

    authText = document.createElement('div');
    authText.setAttribute('class', module+'_dark userText');
    authText.setAttribute('className', module+'_dark userText');
    
    authText1 = document.createTextNode("Added by "); //<b>"+aReviews['reviews'][i]['reviewerName']+"</b> on <b>"+aReviews['reviews'][i]['reviewDate']+"</b>. Rating given: ");
    boldText1 = document.createElement('b');
    boldText1.appendChild(document.createTextNode(aReviews['reviews'][i]['reviewerName']));
    authText2 = document.createTextNode(" on "); //<b>"+aReviews['reviews'][i]['reviewerName']+"</b> on <b>"+aReviews['reviews'][i]['reviewDate']+"</b>. Rating given: ");
    boldText2 = document.createElement('b');
    boldText2.appendChild(document.createTextNode(aReviews['reviews'][i]['reviewDate']));
    authText3 = document.createTextNode(". Rating given: ");
    
    authText.appendChild(authText1);
    authText.appendChild(boldText1);
    authText.appendChild(authText2);
    authText.appendChild(boldText2);
    authText.appendChild(authText3);
    
    lastRow = document.createElement('div');
    lastRow.appendChild(authText);
    lastRow.innerHTML = lastRow.innerHTML + aReviews['reviews'][i]['starHTML'];
    reviewDiv.appendChild(lastRow);
        
    review.appendChild(rightQuote);
    review.appendChild(leftQuote);
    review.appendChild(reviewDiv);
    document.getElementById('reviewListFull').appendChild(review);
    bSuccess = true;
  }
  
  window.location = '#review'+aReviews['page'];
  
  rebuildPagination('reviewPaginationBottom', '#review', aReviews['page'], aReviews['iLimit'], aReviews['maxReviews'], 'reviewPaginationTop', aReviews['startReviews'], aReviews['endReviews']);
  
}

/*
  JS PAGINATION FUNCTIONS.
*/

function rebuildPaginationText(paginationDiv, iPage, iPerPage, iStart, iEnd, iMax) {
  paginationTop = document.getElementById(paginationDiv);
  if(paginationTop.hasChildNodes())  {
      while(paginationTop.childNodes.length >= 1) { paginationTop.removeChild( paginationTop.firstChild ); } 
  } 
  extra = '';
  if (!iPage) {
      iPage = 1;
  }
  iEnd = iPerPage * iPage;
  iStart = iEnd + 1 - iPerPage;
  if (iMax > -1) {
      if (iMax) {
          iEnd = Math.min(iPerPage * iPage,iMax);
          extra = " of "+iMax;
          pages = Math.ceil((iMax - 0.1) / iPerPage);
      } else {
          pages = iPage + 1;
      }
      text = "Results "+iStart+" - "+iEnd+extra+".";
  }
  reviewTopText = document.createTextNode(text);
  paginationTop.appendChild(reviewTopText);
  
}

function rebuildPagination(paginationDiv, strPageLink, iPage, iPerPage, iMax, strTextOption, iStart, iEnd) {
  
  if(typeof strTextOption != 'null' || typeof strTextOption != 'undefined') rebuildPaginationText(strTextOption, iPage, iPerPage, iStart, iEnd, iMax);
  
  paginationDiv = document.getElementById(paginationDiv);
  if(paginationDiv.hasChildNodes())  {
      while(paginationDiv.childNodes.length >= 1) { paginationDiv.removeChild( paginationDiv.firstChild ); } 
  }
  baseURL = window.location.href;
  strSplit = baseURL.split(strPageLink);
  baseURL = strSplit[0];
  
  if (typeof iPage == 'undefined' || typeof iPage == 'null') {
    iPage = 1;
  }
  
  // Right, so now we need to calculate
  lastResult = iPerPage * iPage;
  firstResult = lastResult + 1 - iPerPage;

  pages = Math.ceil((iMax - 0.1) / iPerPage);   
  
  linkPages = new Array();
  addAtEnd = Math.max(2,6-iPage);
  addAtStart = Math.max(2,iPage - pages + 5);
  
  start = Math.max(1,iPage - addAtStart);
  end = Math.min(pages,iPage + addAtEnd);
  if (pages < 1) {
      end--;
  }
  
  linkPages[1] = '&lt;&lt; First';
  for (i = start; i <= end; i++) {
      linkPages[i] = i;
  }
  
  if (pages && iMax) {
      linkPages[pages] = 'Last &gt;&gt;';
  }
  
  i = 0;
  aLinks = new Array();
  for (var j in linkPages) {
    
    if(j == iPage) {
      link = document.createElement('span');
      link.setAttribute('class', 'active');
      link.setAttribute('className', 'active');
      
     } else {
      link = document.createElement('a');
      link.setAttribute('href', baseURL+strPageLink+j);
      link.onclick = function(){ setReviewPage(this.href); return false; }
    }
  
    link.innerHTML = linkPages[j];
    
    linkHolder = document.createElement('span');
    linkHolder.setAttribute('class',module+' pagination');
    linkHolder.setAttribute('className', module+' pagination');  
    linkHolder.appendChild(link);
    paginationDiv.appendChild(document.createTextNode(" "));
    paginationDiv.appendChild(linkHolder);
  }
}

function failRating(array) {
  
  var successBanner = document.getElementById('bannerSuccess');
  successBanner.setAttribute('class','alert');
  successBanner.setAttribute('className','alert');
  successBanner.innerHTML = 'There was an error saving your review, please try again.';
}

function savedRating(array) {
  
  var successBanner = document.getElementById('bannerSuccess');
  successBanner.setAttribute('class','success');
  successBanner.setAttribute('className','success');
  successBanner.innerHTML = 'Your review was submitted for approval.';
  
  storedReviewText.value = '';
  storedReviewRating.value = '';
  aStar = new Array();
  aStar['newRating'] = 0;
  aStar['numRatings'] = 0;
  star.ratingSet(aStar, n);
  bRatingSet = false;
}

bRatingSet = false;
function submitRating(iBusiness) {
  
  storedReviewText = document.getElementById('reviewText');
  
  storedReviewRating = document.getElementById('cStarsRating'+iBusiness);
  
  kjax('submitReview', {businessID:iBusiness,reviewText:storedReviewText.value,rating:storedReviewRating.value,module:module}, 'savedRating', 'failRating');
}

// To fire when page loads.
if(window.location.href.split("#review").length > 1) {
  setTimeout("setReviewPage(window.location.href)", 500);
}

function showMore(e) {
  
  iReview = e.id.substr(8);
  
  after = document.getElementById('afterCurtail'+iReview);
  after.style.display = 'inline';
  e.style.display = 'none';
  e.style.paddingLeft = '0px';
  less = document.getElementById('lessLink'+iReview);
  less.style.display = 'inline';
  return false;
}

function showLess(e) {
  
  iReview = e.id.substr(8);
  
  after = document.getElementById('afterCurtail'+iReview);
  after.style.display = 'none';
  e.style.display = 'none';
  more = document.getElementById('moreLink'+iReview);
  more.style.display = 'inline';
  more.style.paddingLeft = '5px';
  return false;
}