var media = null;
var mediaTheater = null;
var artSortDrop = null;
var preloadImgs = new Array();
var preload = new Array();
var prefix = 'http://media1.behance.com/_magIMG/menu/';
preload[0] = prefix+'peopleOn.gif';
preload[1] = prefix+'peopleOff.gif';
preload[2] = prefix+'peopleOver.gif';
preload[3] = prefix+'contentOn.gif';
preload[4] = prefix+'contentOff.gif';
preload[5] = prefix+'contentOver.gif';
preload[6] = prefix+'glossaryOn.gif';
preload[7] = prefix+'glossaryOff.gif';
preload[8] = prefix+'glossaryOver.gif';
for (var i=0;i<preload.length;i++) {
	preloadImgs[i] = new Image();
	preloadImgs[i].src = preload[i];
	//var curLoad = new preloadImg(preload[i]);
}

function goTo(url) {
	window.location = url;	
}

function goToNew(url, target) {
	var target = (target) ? target : '_blank';
	window.open(url, target);
}

function getQueryString() {
	var qs = window.location.search;
	if (qs != '?' && qs != '') {
		var obj = qs.toQueryParams();
		obj = $H(obj);
		return obj;
	} else return false;
}

function openQuoteBox() {
	if ($('quoteArrow')) {
		$('quoteBoxWrap').style.display='block';
		$('quoteBox').style.display='block';
		$('quoteLoad').style.display='block';
		$('quoteArrow').style.visibility='hidden';
		var quoteHeight = $('quoteLoad').getHeight();
		$('quoteBoxWrap').style.height = (quoteHeight+30)+'px';	
		$('quoteLoad').style.display='block';
	}
}

function closeQuoteBox() {
	if ($('quoteArrow')) {
		$('quoteBoxWrap').style.display='none';
		$('quoteBox').style.display='none';
		$('quoteLoad').style.display='none';
		$('quoteArrow').style.visibility='visible';
		$('quoteArrow').style.display='block';
	}
}

Event.observe(window, 'load', function() {
	$$('#headerLinks .fL img').each(function(el){
		var navSrc = el.src;
		if (navSrc.match('Off')) {
			var onSrc = navSrc.replace('Off', 'Over');
			var offSrc = navSrc.replace('Over', 'Off');
		} else {
			var onSrc = navSrc.replace('On', 'On');
			var offSrc = navSrc.replace('Over', 'On');
		}
		
		Event.observe(el, 'mouseover', function(evt) {
			el.src = onSrc;
		});
		Event.observe(el, 'mouseout', function(evt) {
			el.src = offSrc;
		});
	});	
	
	
	if ($('quoteBox')) {
		openQuoteBox();
	}
	if ($('artSort_dropdown')) {
		artSortDrop = new myDropdown('artSort', function(el) {
			selectArtSortDrop(el);
		});
		artSortDrop.setRunCallBack(false);
		
		var qsObj = getQueryString();
		var sortBy;
		if (qsObj && qsObj.get('order_by')) sortBy = qsObj.get('order_by');
		else sortBy = 'Most_Recent';
		if ($('artSort_Op_'+sortBy)) {
			artSortDrop.makeSelection($('artSort_Op_'+sortBy));	
		} else {
			alert('Unable to find sortBy: '+sortBy);	
		}
	}
	if ($('artRealm_dropdown')) {
		artRealmDrop = new myDropdown('artRealm', function(el) {
			selectArtRealmDrop(el);
		});
		artRealmDrop.setRunCallBack(false);
		
		var qsObj = getQueryString();
		var realm;
		if (qsObj && qsObj.get('realm')) realm = qsObj.get('realm');
		else realm = 'All_Realms';
		if ($('artRealm_Op_'+realm)) {
			artRealmDrop.makeSelection($('artRealm_Op_'+realm));	
		} else {
			alert('Unable to find realm: '+realm);	
		}
	}
	$$('#headerWrap .fL img').each(function(el){
		var navSrc = el.src;
		if (navSrc.match('Off')) {
			var onSrc = navSrc.replace('Off', 'Over');
			var offSrc = navSrc.replace('Over', 'Off');
		} else {
			var onSrc = navSrc.replace('On', 'On');
			var offSrc = navSrc.replace('Over', 'On');
		}
		
		Event.observe(el, 'mouseover', function(evt) {
			el.src = onSrc;
		});
		Event.observe(el, 'mouseout', function(evt) {
			el.src = offSrc;
		});
	});
	
	if ($$('#viralIcons img').length > 0) {
		setupViral();	
	}
});

function appendQS(url, str) {
	var qsObj = getQueryString();
	if (qsObj && qsObj.get(str) && qsObj.get(str) != '') {
		url += '&'+str+'='+qsObj.get(str);
	}
	return url;
}
function selectArtSortDrop(el) {
	curItem = el.id;
	curItem = curItem.replace('artSort_Op_', '');
	var url = '/Filters?order_by='+curItem;
	url = appendQS(url, 'realm');
	//url = appendQS(url, 'page');
	goTo(url);
}
function selectArtRealmDrop(el) {
	curItem = el.id;
	curItem = curItem.replace('artRealm_Op_', '');
	var url = '/Filters?realm='+curItem;
	url = appendQS(url, 'order_by');
	//url = appendQS(url, 'page');
	goTo(url);
}
function dynFunc(func) {
	eval('mediaTheater.'+func+'()');	
}

var myDropdown = Class.create();
myDropdown.prototype = {
	_name : null,
	_callback : null,
	_runCallback : null,
	
	initialize : function (name, callback) {
		this._name = name;
		this._callback = callback;
		this._runCallback = true;
		
		var self = this;
		
		$(name+'_dropdownBack').onclick= function () { self.toggleOptions() };
		
		this.loadEvents();
		
		self = this;
		Event.observe(document.body, 'click', function (evt) {
			var el = Event.element(evt);
			var name = self._name;
			
			if (el.id != name+'_dropdown' && 
				el.id != name+'_dropdownBack' && 
				el.id != name+'_dropdownPad' && 
				el.id != name+'_selection' && 
				el.id != name+'_arrow' && 
				el.id != name+'_arrowIMG' && 
				el.id != name+'_options' && 
				el.className != 'dropOption' &&
				el.parentNode.className != 'dropOption' &&
				el.parentNode.parentNode.className != 'dropOption'
			) {
				if ($(name+'_options') && $(name+'_options').style.display == 'block') self.toggleOptions();
			}
		});
	
	},
	
	setRunCallBack : function(bool) {
		this._runCallback = bool;
	},
	
	loadEvents : function() {
		var self = this;
		$$("#"+this._name+"_options .dropOption").each(function(el) {
			Event.observe(el, 'click', function() { self.makeSelection(el) });
		});	
	},
	
	decideShown : function (selEle) {
		var self = this;
		if ($(this._name+'_selection')) {
			$$("#"+this._name+"_options .dropOption").each(function(el) {
				if (selEle.id == el.id) {
					if ($(self._name+'_selection')) $(self._name+'_selection').update(el.firstChild.innerHTML);
					el.style.display = 'none';
				} else {
					el.style.display = 'block';
				}
			});
		}
		
		
	},
	
	makeSelection : function(el) {
		var curID = el.id;
		var convention = this._name+'_Op_';
		var curSelection = curID.replace(convention, '');
		this.setDropSelection(curSelection);
		if ($(this._name+'_selection')) {
			$(this._name+'_selection').update(el.firstChild.innerHTML);
		}
		this.decideShown(el);
		var ops = $(this._name+'_options');
		if (ops.style.display == 'block') this.toggleOptions();
		
		//if false it will skip the beat and set it back after
		if (this._runCallback) {
			this._callback(el);
		}
		else this.setRunCallBack(true);
	},
	
	setDropSelection : function(id) {
		this._dropSelection = id;
		return this._dropSelection;
	},
	
	getDropSelection : function() {
		return this._dropSelection;
	},
	
	toggleOptions : function() {
		var ops = $(this._name+'_options');
		if (ops.style.display == '' || ops.style.display == 'none') {
			ops.style.display = 'block';
		} else {
			ops.style.display = 'none';
		}
	}
}

var myPopup = Class.create();
myPopup.prototype = {
	_pOptions : null,
	initialize : function(callback, popOptions) {
		var callback = (callback) ? callback : null;
		this._pOptions = (popOptions) ? popOptions : null;
		if (!$('outerDIV')) {
			var ClayCreation = document.createElement('div');
			ClayCreation.id = "outerDIV";
			ClayCreation.name = "outerDIV";
			ClayCreation.style.position = "absolute";
			document.body.appendChild(ClayCreation);
	
			var innerDIV =  document.createElement('div'); //create DIV
			innerDIV.style.position = "absolute";
			innerDIV.id = 'innerDIV';
			innerDIV.name = 'innerDIV';
			document.body.appendChild(innerDIV); 

			$('outerDIV').className = 'outerDIV';
			$('innerDIV').className = 'innerDIV';
			
			
			$('innerDIV').update('Loading...');
			
			
			
			this.posPopup(popOptions);
			

			
			callback(popOptions);
		} else { this.clearClay(); }
	},
	posPopup : function() {
		var popOptions = this._pOptions;
		var innerHeight = $('innerDIV').getHeight();
		var innerWidth = $('innerDIV').getWidth();
		var outerHeight = (innerHeight+34);
		var outerWidth = (innerWidth+34);
		$('outerDIV').style.display='none';
		$('innerDIV').style.display='none';
		$('outerDIV').style.height = outerHeight+'px';
		$('outerDIV').style.width = outerWidth+'px';
		
		if (!popOptions || (popOptions && !popOptions.get('center')) || (popOptions && popOptions.get('center') == 'viewport')) {
		
			var viewWidth = document.viewport.getWidth();
			var viewHeight = document.viewport.getHeight();
			
			var scrollPos = document.viewport.getScrollOffsets();
			var scrollPosX = scrollPos[0];
			var scrollPosY = scrollPos[1];	
	
			
			//place innerDIV horizontally centered
			ScrollWin = scrollPosX + (viewWidth/2);
			newInnerLeft = (ScrollWin) - (innerWidth/2);
			$('innerDIV').style.left = newInnerLeft+"px";
			
			//place innerDIV vertically centered
			ScrollWin = scrollPosY + (viewHeight/2);
			newInnerTop = (ScrollWin) - (innerHeight/2);
			$('innerDIV').style.top = newInnerTop+"px";
			
			//place outerDIV horizontally centered
			ScrollWin = scrollPosX + (viewWidth/2);
			newouterLeft = (ScrollWin) - (outerWidth/2);
			$('outerDIV').style.left = newouterLeft+"px";
			
			//place outerDIV vertically centered
			ScrollWin = scrollPosY + (viewHeight/2);
			newouterTop = (ScrollWin) - (outerHeight/2);
			$('outerDIV').style.top = newouterTop+"px";
		
		} else {
			
			if (popOptions.get('center') == 'element') {
				if (popOptions.get('elementName')) {
					 var eleName = popOptions.get('elementName');
					 var eleObj = $(eleName);
					 var eleHeight = eleObj.getHeight();
					 var eleWidth = eleObj.getWidth();
					 var offTop = (eleHeight/2)-($('outerDIV').getHeight()/2);
					 var offLeft = (eleWidth/2)-($('outerDIV').getWidth()/2);
					 $('outerDIV').clonePosition(eleObj, { 'setWidth' : false, 'setHeight' : false, 'offsetTop' : offTop, 'offsetLeft' : offLeft});
				} else alert('Uknown elementName');
			} else alert('Unknown center type');
			
		}
		$('outerDIV').style.display='block';
		$('innerDIV').style.display='block';
	},
	clearClay : function() {
		$('outerDIV').remove();
		$('innerDIV').remove();
	}
}

function sendArticlePop(url) {
	curPop = new myPopup(sendArticle, $H({'url' : url}));
}

function sendArticle(args) {
	var url = args.get('url');
	new Ajax.Request('/_ajax/popups/articleToFriend.php?url='+url, {
		method : 'get',
		onComplete : function(transport) {
			$('outerDIV').style.visibility = 'hidden';
			$('innerDIV').update(transport.responseText);
			curPop.posPopup();
			$('outerDIV').style.visibility = 'visible';
			
		}
	});
}

function sendEmailFriend() {
	if ($F('friend_emails') != '') {
		new Ajax.Request('/_ajax/popups/action/sendArticleToFriend.php', {
			method : 'post',
			parameters : $('sendFriendForm').serialize(true),
			onComplete : function(transport) {
				curPop.clearClay();
			}
		});	
	}
}

function proposeEditPop(the_id) {
	curPop = new myPopup(proposeEdit, $H({'the_id' : the_id}));
}

function proposeEdit(args) {
	var the_id = args.get('the_id');
	new Ajax.Request('/_ajax/popups/proposeGlossary.php?id='+the_id, {
		method : 'get',
		onComplete : function(transport) {
			$('outerDIV').style.visibility = 'hidden';
			$('innerDIV').update(transport.responseText);
			curPop.posPopup();
			$('outerDIV').style.visibility = 'visible';
			
		}
	});
}

function sendProposeEdit() {
	if ($F('additional_comments') != '') {
		new Ajax.Request('/_ajax/popups/action/sendProposeGlossary.php', {
			method : 'post',
			parameters : $('proposeForm').serialize(true),
			onComplete : function(transport) {
				curPop.clearClay();
			}
		});	
	}
}

MediaTheater = Class.create();
MediaTheater.prototype = {
	_id : null,
	_items : null,
	_itemIndex : 0,
	_lastIndex : null,
	
	initialize : function (the_id) {
		this._id = the_id;
		var self = this;
		new Ajax.Request('/_ajax/theater/getMediaIDs.php?id='+the_id, {
			onComplete : function (transport) {
				var string = transport.responseText;
				self._items = string.split('|');
				self._lastIndex = (self._items.length)-1;
				self.setArrows();
			}
		});
	},
	setArrows : function() {
		var index = this._itemIndex;
		var self = this;
		if ($('imageSelection')) {
			$('imageSelection').onclick = function() {
				var newIndex = index+1;
				if (newIndex > self._lastIndex) newIndex = 0;
				self.selectMedia(newIndex);
			}	
		}
		$('mediaPrevious').onclick = function() {
			var newIndex = index-1;
			if (newIndex < 0) newIndex = self._lastIndex;
			self.selectMedia(newIndex);
		}
		
		$('mediaNext').onclick = function() {
			var newIndex = index+1;
			if (newIndex > self._lastIndex) newIndex = 0;
			self.selectMedia(newIndex);
		}
	},
	selectMedia : function(index) {
		var id = this._items[index];
		var self = this;
		new Ajax.Request('/_ajax/theater/getMedia.php?art_id='+this._id+'&id='+id, {
			onComplete : function (transport) {
				self._itemIndex = index;
				$('mediaWidget').update(transport.responseText);
				
				self.setArrows();
				closeQuoteBox();
			}
		});
	},
	viewGallery : function() {
		
		new Ajax.Request('/_ajax/theater/gallery.php?art_id='+this._id, {
			onComplete : function (transport) {
				$('mediaWidget').update(transport.responseText);
				closeQuoteBox();
			}
		});
	},
	viewItem : function() {
		this.selectMedia(this._itemIndex);
		
	}
	
}

function hideArea(obj) {
	obj.style.display='none';	
}

function blockArea(obj) {
	obj.style.display='block';	
}

function peopleMore(num) {
		hideArea($('peopleShortBlurb'+num));
		hideArea($('peopleMore'+num));
		blockArea($('peopleLongBlurb'+num));
		blockArea($('peopleLess'+num));
}

function peopleLess(num) {
	blockArea($('peopleShortBlurb'+num));
	blockArea($('peopleMore'+num));
	hideArea($('peopleLongBlurb'+num));
	hideArea($('peopleLess'+num));
}

function articleRelations(page, art_id) {
	new Ajax.Request('/_ajax/pagination/articleRelations.php?page='+page+'&art_id='+art_id, {
		onComplete : function(transport) {
			$('relatedArticles').update(transport.responseText);	
		}
	});
}

function productRelations(page, prod_id) {
	new Ajax.Request('/_ajax/pagination/productRelations.php?page='+page+'&prod_id='+prod_id, {
		onComplete : function(transport) {
			$('relatedProducts').update(transport.responseText);	
		}
	});
}

function glosArticleRelations(page, glos_id) {
	new Ajax.Request('/_ajax/pagination/glosArticleRelations.php?page='+page+'&glos_id='+glos_id, {
		onComplete : function(transport) {
			$('relatedArticles').update(transport.responseText);	
		}
	});
}

function glosProductRelations(page, glos_id) {
	new Ajax.Request('/_ajax/pagination/glosProductRelations.php?page='+page+'&glos_id='+glos_id, {
		onComplete : function(transport) {
			$('relatedProducts').update(transport.responseText);	
		}
	});
}

function articleComment(page, art_id) {
	new Ajax.Request('/_ajax/pagination/articleComments.php?page='+page+'&art_id='+art_id, {
		onComplete : function(transport) {
			$('commentsArea').update(transport.responseText);	
		}
	});
}

function submitComment() {
	$('comPost').update('Posting Comment...');
	new Ajax.Request('/_ajax/postComment.php', {
		method : 'post',
		parameters : $('addCommentForm').serialize(true),
		onComplete : function(transport) {
			$('commentsArea').update(transport.responseText);
		}
	});
}

function enterSubmit(e, submit){if(e&&e.which){e=e; characterCode=e.which}else{characterCode = e.keyCode}if (characterCode == 13){if(submit=="valSideSignIn")valSideSignIn();if(submit=="valSignIn")valSignIn();if (submit == "valCheckoutOne")valCheckoutOne();if (submit == "valUniNews") valUniNews();}}

function appreciateArticle(art_id) {
	var apps = $('appsNum').innerHTML;
	apps = parseInt(apps);
	new Ajax.Request('/_ajax/appreciateArticle.php?art_id='+art_id, {
		onComplete : function(transport) {
			var newApp = apps+1;
			$('appsNum').update(newApp);
			$('articleApp').update('<img src="/_img/buttons/appreciate_it_thankyou.gif" alt="Thank You" title="Thank You" />');
		}
	});
}

function valUniNews() {
	errors = new Array();
	errors[0] = checkEmail("letter_email", 1);
	errors[1] = checkName("letter_name", 1);
	if (searchErrors(errors) == 0)
		$('uni_newsletter').submit();

}

function searchErrors(errors) {
	errorsExist = 0;
	for (i=0;i<errors.length;i++)
	{
		if (errors[i] != "")
		{
			errorsExist = 1;
			break;	
		}
	}
	return errorsExist;
}

function checkEmail(fieldName, required) {
	if ($(fieldName) != null) fieldVal = $(fieldName).value;	
	else fieldVal = "";
	
	innerVal = "";
	
	if (fieldVal != "E-mail Address" && fieldVal != "" && fieldVal != null && fieldVal != "undefined")
	{
		if (!fieldVal.match(/^[A-Za-z0-9_\.-]+@[A-Za-z0-9_\.-]+\.[A-Za-z0-9_-]+$/))
			innerVal = "You must enter a valid e-mail.";
	}
	else 
		if (required == 1) innerVal = "Required Field.";
	
	$(fieldName+'Error').innerHTML = innerVal;
	return innerVal;
}

function checkName(fieldName, required) {
	if ($(fieldName) != null) fieldVal = $(fieldName).value;	
	else fieldVal = "";
	innerVal = "";
	
	if (fieldVal != "Name" && fieldVal != "" && fieldVal != null && fieldVal != "undefined")
	{
		if (!fieldVal.match(/^[A-Za-z\'\. -]+$/))
			innerVal = "Only letters, apostrophes, periods, and dashes may be used.";
	}
	else 
		if (required == 1) innerVal = "Required Field.";

	$(fieldName+'Error').innerHTML = innerVal;
	return innerVal;
}

function placeHomePollValue(radioObj, poll, oldPoll) {
	var pollValue;
	if(!radioObj)	{
		return "";
	}
	var radioLength = radioObj.length;
	if(radioLength == undefined)
		if(radioObj.checked)
			pollValue = radioObj.value;
		else
			return "";
	for(var i = 0; i < radioLength; i++) {
		if(radioObj[i].checked) {
			pollValue = radioObj[i].value;
		}
	}

	if (pollValue) {
		$('pollError').innerHTML = "";
		if (oldPoll == 1) {
			new Ajax.Request('/_ajax/voteOldPoll.php?poll='+poll+'&vote='+pollValue, {
				method : 'get',
				onComplete : function(transport) {
					$('oldPollArea').update(transport.responseText);
				}
			});
		} else {
			new Ajax.Request('/_ajax/voteHomePoll.php?poll='+poll+'&vote='+pollValue, {
				method : 'get',
				onComplete : function(transport) {
					$('poll_results').update(transport.responseText);
				}
			});
		}
		
	} else {
		$('pollError').update("You must make a choice!");
	}
}

function addTo(action, from) {
	var title = encodeURIComponent(document.title);
	var url = encodeURIComponent(location.href);
	if (action == "bookmark")
	{
		if (window.sidebar) { // Mozilla Firefox Bookmark
			window.sidebar.addPanel(title, url,"");
		} else if( window.external ) { // IE Favorite
			window.external.addFavorite(url, title); }
		else  { 
			$('toolError').innerHTML = "<p>&nbsp;</p><p>Safari does not support this feature.</p><p>Please hit CMD + D.</p>";
			// Opera Hotlist
			return true; }
	} else {
		var from = (from) ? from : 'dropsort';
		window.open('/_inc/addTo.php?action='+action+'&url='+url+'&title='+title+'&from='+from, '_blank');
	}
}

var viralIcon = {
	over : function(evt) {
		var overImg = Event.element(evt);
		var viralWrap = document.createElement('div');
		viralWrap.className = 'viralWrap';
		viralWrap.id = 'viralWrap';
		document.body.appendChild(viralWrap);
		var viralTxt = document.createElement('div');
		viralTxt.className = 'viralTxt';
		viralTxt.id = 'viralTxt';
		$('viralWrap').appendChild(viralTxt);
		$('viralTxt').update(overImg.alt);
		Position.clone($('viralIcons'), $('viralWrap'), {setHeight: false, offsetTop: -29});
		
	},
	
	out : function(evt) {
		var outImg = Event.element(evt);
		$('viralWrap').remove();
	}
}

function setupViral() {
	$$('#viralIcons img').each(function(el) {
		viralIcon.over = viralIcon.over.bindAsEventListener(viralIcon);
		Event.observe($(el), 'mouseover', viralIcon.over);
		viralIcon.out = viralIcon.out.bindAsEventListener(viralIcon);
		Event.observe($(el), 'mouseout', viralIcon.out);
	});	
}