document.domain = 'portlandmercury.com';

function addLoadEvent(func) {
  var oldonload = window.onload;
  if (typeof window.onload != 'function') {
    window.onload = func;
  } else {
    window.onload = function() {
      oldonload();
      func();
    }
  }
}

function getElementsByClass(searchClass,node,tag) {
	var classElements = new Array();
	if ( node == null )
		node = document;
	if ( tag == null )
		tag = '*';
	var els = node.getElementsByTagName(tag);
	var elsLen = els.length;
	var pattern = new RegExp("(^|\\s)"+searchClass+"(\\s|$)");
	for (i = 0, j = 0; i < elsLen; i++) {
		if ( pattern.test(els[i].className) ) {
			classElements[j] = els[i];
			j++;
		}
	}
	return classElements;
}

function insertAfter(newElement,targetElement) {
  var parent = targetElement.parentNode;
  if (parent.lastChild == targetElement) {
    parent.appendChild(newElement);
  } else {
    parent.insertBefore(newElement,targetElement.nextSibling);
  }
}

function addClass(element,value) {
  if (!element.className) {
    element.className = value;
  } else {
    newClassName = element.className;
    newClassName+= " ";
    newClassName+= value;
    element.className = newClassName;
  }
}

function showHide(togglethisID,imgID) {
	// imgID usage (optional): if image to be swapped is expand-image.gif, will be replaced with expand-image-toggle.gif
	// ensure that the -toggle image exists on the server
	if (!document.getElementById(togglethisID)) return true;
	var theElement = document.getElementById(togglethisID);
	if (document.getElementById(imgID)) {
		var theImg = document.getElementById(imgID);
		// using stupid IE-specific getAttribute "iFlag" to prevent it returning an absolute path
		var imgName = theImg.getAttribute("src",2).split(".")[0];
		var imgName = imgName.split("-toggled")[0];
	}
	if (theElement.style.display == 'none') {
		theElement.style.display = 'block';
		if (theImg) {
			theImg.setAttribute("src", imgName+"-toggled.gif");
		}
	} else if (theElement.style.display == 'block') {
		theElement.style.display = 'none';
		if (theImg) {
			theImg.setAttribute("src", imgName+".gif");
		}
	}
	return false;
}

function setupLinkBehavior() {
	if (!document.getElementsByTagName) return false;
	if (!document.getElementById) return false;
	var links = document.getElementsByTagName('a');
	for (var i=0;i<links.length;i++) {
		if (links[i].className.match('playLink') || links[i].className.match('playlink')) {
			links[i].onclick = function() {
					var mp3 = this.getAttribute('href');
					var title = this.getAttribute('title');
					OpenWindow('http://portlandmercury.com/scripts/flashAudioPlayer.php?f='+mp3+'&amp;t='+title,'300','50','player');
					return false;
				};
		} else if (links[i].className.match('emailThisLink')) {
			links[i].onclick = function() {
					OpenWindow(this.getAttribute('href'),'790','640');
					return false;
				};
		} else if (links[i].className.match('tglink')) {
			links[i].onclick = function() {
				tabToggler(this);		
				return false;
			};
		}
		if (links[i].getAttribute('href') && !links[i].getAttribute('target')) {
			var thisURL = links[i].getAttribute('href').replace(/^http:\/\//,'');
			if (thisURL.match(/^(.*\.)?portlandmercury\.com|^\/|^#|^\?/)) {
				links[i].setAttribute('target','_self');
			} else {
				links[i].setAttribute('target','_blank');
			}
		}
	}
}

function animateAnchorLinks() {
	// WARNING: only use this if prototype and scriptaculous effects are being loaded
	// should probably do some checking to make sure functions are available
	// also, doesn't seem to work in IE
	if (!$$('a')) return false;
	var all_links = $$('a');
	all_links.each(function(thelink) {
			if (thelink.getAttribute('href')) {
				if (thelink.getAttribute('href').match(/^#/) && $(thelink.getAttribute('href').split('#')[1])) {
					thelink.onclick = function() {
						new Effect.ScrollTo(thelink.getAttribute('href').split('#')[1]);
						return false;
					}
				}
			}
		});
}

/* Cookie Functions */

function setCookie(cookieName,cookieValue,nDays) {
	 var today = new Date();
	 var expire = new Date();
	 if (nDays==null || nDays==0) nDays=1;
	 expire.setTime(today.getTime() + 3600000*24*nDays);
	 document.cookie = cookieName+"="+escape(cookieValue) + "; expires="+expire.toGMTString() + "; path=/";
}
	
function getCookie(cookieName) {
	if (document.cookie.length > 0) {
		cookieStart = document.cookie.indexOf(cookieName + "=");
		if (cookieStart != -1) {
			cookieStart = cookieStart + cookieName.length+1;
			cookieEnd = document.cookie.indexOf(";",cookieStart);
			if (cookieEnd == -1) cookieEnd = document.cookie.length;
			return unescape(document.cookie.substring(cookieStart,cookieEnd));
		}
	}
	return "";
}

function acceptsCookies() {
	var cookieName = 'strCheck';
	var timestamp =  new Date().getTime();
	setCookie(cookieName,timestamp,'1');
	if (getCookie(cookieName) == timestamp) {
		document.cookiesOn = true;
	} else {
		document.cookiesOn = false;
	}
}

/* scroller box */

function Scroller() {
	var target, playButton, pauseButton, dataURL, itemCount, initCount, delay, slide;
	this.setTarget = function(value) { target = value; };
	this.setURL = function(value) { dataURL = value; };
	this.setItemCount = function(value) { itemCount = value; };
	this.setInitCount = function(value) { initCount = value; };
	this.setDelay = function(value) { delay = value; };
	this.setPlayButtonID = function(value) { playButton = value; };
	this.setPauseButtonID = function(value) { pauseButton = value; };
	this.setHtmlConstructor = function(value) { constructHTML = value; };
	this.setSlide = function(value) { slide = value; };
	// set defaults
	if (!itemCount) itemCount = 30;
	if (!initCount) initCount = 0;
	if (!delay) delay = 8;
	if (!slide) slide = false;
	// internal variables
	var REQUIRED_VERSIONS = { 'Prototype' : '1.5.1.1', 'Scriptaculous' : '1.7.1' };
	var count = 0;
	var data = null;
	var myPE = null;
	var maxItems = (initCount != 0) ? initCount * 2 : 10;
	this.init = function() {
		if (!require('Prototype') || !target || !dataURL || !$(target) || !constructHTML) return;
		if ($(pauseButton) && $(playButton)) {
			Event.observe(pauseButton, 'click', function(e) {
				swapButtons('play');
				myPE.stop();
				Event.stop(e);
			});
			Event.observe(playButton, 'click', function(e) { startScroller(); Event.stop(e); });
		}
		Event.observe(target, 'mouseover', function() {
			swapButtons('play');
			myPE.stop();
		});
		Event.observe(target, 'mouseout', startScroller);
		getData();
	};
	var getData = function() {
		new Ajax.Request(dataURL, {
			method: 'get',
			parameters: { q : itemCount },
			onSuccess: function(transport) {
				data = transport.responseText.evalJSON();
				loadInitial(data);
			}
		});
	};
	var loadInitial = function(data) {
		data.each(function(i) {
			if (count == initCount) throw $break;
			var newhtml = constructHTML(i, target+'_item', count);
			new Insertion.Top($(target), newhtml);
			++count;
		});
		startScroller();
	};
	var startScroller = function() {
		swapButtons('pause');
		if (!$(target+'_inner') && slide) {
			var innerDiv = document.createElement('div');
			innerDiv.id = target+'_inner';
			var existingItems = $(target).immediateDescendants();
			existingItems.each(function(i) {
				var r = i.remove();
				innerDiv.appendChild(r);
			});
			$(target).appendChild(innerDiv);
		}
		myPE = new PeriodicalExecuter(function(pe) {
			var newhtml = constructHTML(data[count], target+'_item', count);
			if (slide) {
				var lastThing = ($(target).firstDescendant().id != target+'_inner') ? $(target).firstDescendant().remove() : null;
				if (lastThing) $(target+'_inner').insertBefore(lastThing, $(target+'_inner').firstDescendant());
			}
			new Insertion.Top($(target), newhtml);
			var newThing = $(target).firstDescendant();
			if (require('Scriptaculous')) {
				var offset = newThing.offsetHeight;
				newThing.hide();
				if (slide) new Effect.Move($(target+'_inner'), { x:0, y:offset, queue: {position:'end', scope:'scroller'} });
				new Effect.Appear(newThing, {queue: {position:'end', scope:'scroller'} });
			}
			++count;
			if (count >= data.length) count = 0;
			var itemsArray = (slide) ? $(target+'_inner').immediateDescendants() : $(target).immediateDescendants();
			if (itemsArray.length > maxItems) {
				$(itemsArray.last()).remove();
			}
		}, delay);
	};
	var swapButtons = function(which) {
		if ($(pauseButton) && $(playButton)) {
			switch(which) {
				case 'pause':
					$(pauseButton).show();
					$(playButton).hide();
					break;
				case 'play':
					$(playButton).show();
					$(pauseButton).hide();
					break;
			}
		}
	};
	var require = function(library) {
		if ((typeof window[library] == 'undefined') || (convertVersionString(window[library].Version) < convertVersionString(REQUIRED_VERSIONS[library]))) {
			return false;
		} else {
			return true;
		}
	};
	var convertVersionString = function(versionString) {
		var r = versionString.split('.');
    return parseInt(r[0])*100000 + parseInt(r[1])*1000 + parseInt(r[2]);
	};
}

var chowScrollerConstructor = function(json, prefix, index) {
	var rating_stars = '';
	for (var i=0;i<json.stars;i++) {
		rating_stars += '<img src="\/images\/ratings\/one-star-small.gif" alt="" \/>';
	}
	for (var j=0;j<(5-json.stars);j++) {
		rating_stars += '<img src="\/images\/ratings\/no-star-small.gif" alt="" \/>';
	}
	html = '<div class="scrollerItem" id="'+prefix+index+'"><p class="revHeader"><strong><a href="'+json.url+'">'+json.location.unescapeHTML()+'<\/a><\/strong><br \/>'+rating_stars+'<br \/><span class="revBy">by <em>'+json.screenName+'<\/em><\/span><\/p><p>'+json.excerpt+'<\/p><p class="revRead"><a href="'+json.url+'#diningComments">more &raquo;<\/a><\/p><\/div>';
	return html;
}
function initChowScroller() {
	var reviewScroller = new Scroller();
	reviewScroller.setTarget('reviewScroller');
	reviewScroller.setURL('/portland/Includes/LocationReviews/ReviewsJSON');
	reviewScroller.setItemCount(50);
	reviewScroller.setDelay(6);
	reviewScroller.setPlayButtonID('playButton');
	reviewScroller.setPauseButtonID('pauseButton');
	reviewScroller.setHtmlConstructor(chowScrollerConstructor);
	reviewScroller.setSlide(false);
	reviewScroller.init();
}

function getRandomNumber(range) {
	return Math.floor(Math.random() * range);
}

function getRandomChar() {
	var chars = "0123456789abcdefghijklmnopqurstuvwxyzABCDEFGHIJKLMNOPQURSTUVWXYZ";
	return chars.substr(getRandomNumber(62), 1);
}

function getRandomLetter() {
	var chars = "abcdefghijklmnopqurstuvwxyz";
	return chars.substr(getRandomNumber(26), 1);
}

function randomID(size) {
	var str = "";
	for(var i = 0; i < size; i++) {
		str += getRandomChar();
	}
	return str;
}

function Popit (url, name, height, width) {
		window.open(url, name, 'height='+height+',width='+width+',scrollbars=yes,menubar=no,resizable=no')
}

function OpenWindow(url, width, height, name, options) {
	var name = (name == null) ? 'Mercury' : name.replace(/[^a-z]/gi, '');
	var options = (options == null) ? {'scrollbars':'yes','menubar':'no','resizable':'yes','status':'yes'} : options;
	if (!options['scrollbars'] || !options['scrollbars'].match(/^(yes|no)$/)) {
		options['scrollbars'] = 'yes';
	}
	if (!options['menubar'] || !options['menubar'].match(/^(yes|no)$/)) {
		options['menubar'] = 'no';
	}
	if (!options['resizable'] || !options['resizable'].match(/^(yes|no)$/)) {
		options['resizable'] = 'yes';
	}
	if (!options['status'] || !options['status'].match(/^(yes|no)$/)) {
		options['status'] = 'yes';
	}
	var toolbars = options['menubar'];
	var atts = 'height='+height+', width='+width+', scrollbars='+options['scrollbars']+', menubar='+toolbars+', toolbar='+toolbars+', resizable='+options['resizable']+', status='+options['status'];
	window.open(url, name, atts);
	return false;
}

addLoadEvent(setupLinkBehavior);
addLoadEvent(acceptsCookies);
addLoadEvent(initChowScroller);