/*
*  stranger.js
*
*  gloabl javascript for thestranger.com
*/

/* Utility Functions */

document.domain = 'thestranger.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 idxPageDimensions () {
    var res = [0,0];
    var woh = ["Width","Height"];
    var doc = document.documentElement ?
        document.documentElement : document.body;
    
    for (var i = 0; i < woh.length; i++) {
        if (doc["client" + woh[i]] && doc["client" + woh[i]]) {
    		res[i] = doc["client" + woh[i]];
    	}

    	if (doc["scroll" + woh[i]] && doc["scroll" + woh[i]] > res[i]) {
    		res[i] = doc["scroll" + woh[i]];
    	}

    	if (doc["offset" + woh[i]] && doc["offset" + woh[i]] > res[i]) {
    		res[i] = doc["offset" + woh[i]];
      	}

      	if (self["inner" + woh[i]] && self["inner" + woh[i]] > res[i]) {
      	    res[i] = self["inner" + woh[i]];
      	}
    }
      	  	
  	return res;
}

function formatDate(date,format_code) {
	if ((typeof date == "object") && (date instanceof Date)) {
		switch(format_code) {
	  	case 1: // ex: 2006-10-23
	    	var mymonth = date.getMonth() + 1;
	    	return date.getFullYear() + '-' + mymonth + '-' + date.getDate();
	    	break;
	    case 2: // ex: Monday, Oct. 23
	      return weekday[date.getDay()] + ', ' + month[date.getMonth()] + '. ' + date.getDate();
	      break;
	  }
	} else {
		return false;
  }
}

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 anchorJump(anchorName) {
	// probably should use Scriptaculous Effect.ScrollTo() instead, which doesn't require YUI (but does require scriptaculous and prototype, of course)
	// it's also a nicer effect
	// SEE animateAnchorLinks() below
	for (var i=0;i < document.anchors.length; i++) {
		if (document.anchors[i].name == anchorName) {
			var a = document.anchors[i];
			var pos = YAHOO.util.Dom.getXY(a);
			window.scrollTo(pos[0],pos[1]);
			break;
		}
	}
}

function jumptoID(id) {
	var pos = YAHOO.util.Dom.getXY(document.getElementById(id));
	window.scrollTo(pos[0],pos[1]);
}

/* onload setup functions */

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://www.thestranger.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','550');
					return false;
				};
		} else if (links[i].className.match('toggleLink') || links[i].className.match('togglelink')) {
			links[i].onclick = function() {
				var togglePointer = this.getAttribute('href').split('?')[1].split('=')[0];
				var theElement = document.getElementById('details_'+togglePointer);
				theElement.style.display = 'block';			
				return false;
			};
		}
		if (links[i].getAttribute('href') && !links[i].getAttribute('target')) {
			var thisURL = links[i].getAttribute('href').replace(/^http:\/\//,'');
			if (thisURL.match(/^media\.thestranger\.com\/slideshows(.*)?/)) {
				links[i].onclick = function() {
					OpenWindow(this.getAttribute('href'),'975','720','Slideshow');
					return false;
				};
			} else 	if (thisURL.match(/^(.*\.)?thestranger\.com|^\/|^#|^\?/)) {
				links[i].setAttribute('target','_self');
			} else {
				links[i].setAttribute('target','_blank');
			}
		}
	}
}

function tabToggler(thelink) {
	// NAMING CONVENTIONS:
	// IMPORTANT: The whole thing relies on these conventions being followed correctly.
	//
	// Each instance should have some kind of descriptive name (called <name> in examples below), which will be the same throughout the instance.
	// Each tab has an identifier (<identifier> below) that is shared between the tab and the related content container.
	// Tab (might be an <li> or the link itself): id = tgtab_<name>_<identifier>
	// Container (most likely a div): id = tgcontainer_<name>_<identifier>
	// NOTE: <name> and <identifier> must not contain underscores.
	// ALSO NOTE: assumes the other tabs are the same kind of element as the initial one
	//
	// EXAMPLE:
	// <ul name="eventdetails"> (name attr is not required, but holds things together nicely, I think)
	// <li id="tgtab_eventdetails_basics">
	//	<a class="toggleLink" href="...">The Basics</a>
	// </li>
	// <div id="tgcontainer_eventdetails_basics">Some Content</div>
	// 
	// WHAT HAPPENS:
	// Basics <li> gets a class of <name>_current, using whatever name is used
	// (This happens to whatever element has the 'tgtab' id, doesn't have to be an <li>)
	// All other tgtabs that match 'eventdetails' have class removed (see possible improvements)
	// The matching tgcontainer element has it's display set to block, all others with ids that match 'eventdetails' are set to none
	//
	// POSSIBLE IMPROVEMENTS:
	// would be better if it didn't replace the class attribute entirely, but just added/removed the 'current' class (prototype can do this)
	// whole thing could be more efficient
	
	var clickeditem = thelink.parentNode;
	var thelist = clickeditem.parentNode;
	var listitems = thelist.getElementsByTagName('a');
	for (var i=0;i<listitems.length;i++) {
		if (listitems[i].getAttribute('id') == clickeditem.getAttribute('id')) {
			listitems[i].parentNode.className = activeclass;
			
		} else {
			listitems[i].parentNode.className = '';
		}
	}
}

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').match(/^#/)) {
				thelink.onclick = function() {
					new Effect.ScrollTo(thelink.getAttribute('href').split('#')[1]);
					return false;
				}
			}
		});
}

function prepareForms() {
  for (var i=0; i<document.forms.length; i++) {
    var thisform = document.forms[i];
    prepareTextInputFields(thisform);
  }
}

function prepareTextInputFields(whichform) {
	var inputs = whichform.getElementsByTagName('input');
	for (var i=0;i<inputs.length;i++) {
		var element = inputs[i];
		if (element.getAttribute('type') == 'text') {
			element.value = element.getAttribute('title');
			element.onfocus = function() {
				if (this.value == this.getAttribute('title')) {
					this.value = '';
				}
			};
			element.onblur = function() {
				if (this.value == '') {
					this.value = this.getAttribute('title');
				}
			};
		}
	}
}

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

/* simple utilities - many redundancies here, rewriting/consolidating is in order */

function jumpto(x) {
if (document.jumpForm.jumpmenu.value != "null") {
	document.location.href = x
	}
}

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

function OpenWindow(url, width, height, name) {
	var name = (name == null) ? 'The Stranger' : name;
	window.open(url, name, 'height='+height+',width='+width+',scrollbars=yes,menubar=no,resizable=yes,status=yes');
	return false;
}

/* Ajax Utilities */

function displayLoading(element,imgpath,imgclass,clobber) {
	var image = document.createElement('img');
	image.setAttribute('alt','loading...');
	image.setAttribute('src',imgpath);
	image.id = 'loading';
	image.className = imgclass;
	if (clobber) element.innerHTML = '';
	element.appendChild(image);
}

/* Global Arrays */

var weekday=new Array(7)
weekday[0]="Sunday"
weekday[1]="Monday"
weekday[2]="Tuesday"
weekday[3]="Wednesday"
weekday[4]="Thursday"
weekday[5]="Friday"
weekday[6]="Saturday"

var month=new Array(12)
month[0]="Jan"
month[1]="Feb"
month[2]="Mar"
month[3]="Apr"
month[4]="May"
month[5]="June"
month[6]="July"
month[7]="Aug"
month[8]="Sept"
month[9]="Oct"
month[10]="Nov"
month[11]="Dec"

/* Gloabal Load Events */

addLoadEvent(setupLinkBehavior);
addLoadEvent(acceptsCookies);
addLoadEvent(prepareForms);