/**
* @author Dave
*/

// PrototypeJS Event.onDOMReady extension
try {
    Object.extend(Event, {
        _domReady : function() {
            if (arguments.callee.done) return;
            arguments.callee.done = true;
            if (this._timer) clearInterval(this._timer);
            this._readyCallbacks.each(function(f) { f() });
            this._readyCallbacks = null;
        },
        onDOMReady : function(f) {
            if (!this._readyCallbacks) {
                var domReady = this._domReady.bind(this);
                if (document.addEventListener) document.addEventListener("DOMContentLoaded", domReady, false);
                if (/WebKit/i.test(navigator.userAgent)) {
                    this._timer = setInterval(function() {
                        if (/loaded|complete/.test(document.readyState)) domReady();
                    }, 10);
                }
                Event.observe(window, 'load', domReady);
                Event._readyCallbacks =  [];
            }
            Event._readyCallbacks.push(f);
        }
    });
} catch(e) {
}

Event.onDOMReady(function(){
	// XHTML 1.0 Strict work around for external links
	$$('a[rel*="external"]').each(function(e){
		e.writeAttribute("target","_blank");
	});

	// Automatic text clear
	$$('input.clearField').each(function(e){
		e.observe('focus',function(){
			this.value = "";
		}).observe('blur',function(){
			if(this.value == "") {
				this.value = this.defaultValue;
			}
		});
	});

	// Image roll-over setup
	$$('img.rollOver, input[type="image"].rollOver').each(function(e){
		e.observe('mouseover',function(){
			if (this.src.indexOf("_i.") != -1) {
				this.src = this.src.replace("_i.", "_o.");
			}
		}).observe('mouseout',function(){
			if (this.src.indexOf("_o.") != -1) {
				this.src = this.src.replace("_o.", "_i.");
			}
			if(this.src.indexOf("_a.")) {
				this.src = this.src.replace("_a.","_i.");
			}
		})
		if(e.match("input")) {
			e.observe('mousedown',function(){
				this.src = this.src.replace("_o.","_a.");
			}).observe('mouseup',function(){
				this.src = this.src.replace("_a.","_i.");
			});
		}
	});
	
	// Contact and signup
	$$('.contactType label').each(function(lbl){
		lbl.observe('mouseup',function(){
			// Row highlight interaction, assign selected class to parent row of label
			this.up('.contactType').descendants('li').each(function(e){
				if(e.hasClassName('selected')) {
					e.removeClassName('selected');
				}
			})
			this.up('li').addClassName('selected');
			
			// Set displayed and required fields for contact type
			switch(this.down('input').value) {
				case "publisher":
					var displayFields = new Array('name','email','company','subject','comments');
					var required = new Array('name','email','company','subject','comments');
				break;
				case "advertiser":
					var displayFields = new Array('name','email','company','subject','comments');
					var required = new Array('name','email','company','subject','comments');
				break;
				case "press":
					var displayFields = new Array('name','email','company','comments');
					var required = new Array('name','email','company','comments');
				break;
				case "general":
					var displayFields = new Array('name','email','comments');
					var required = new Array('name','email','comments');
				break;
			}
			
			$('id_required').value = required.join(",");
			$('id_visible').value = displayFields.join(",");
			
			// Parse through all inputs in the contact form and 
			// modify according to selected contact type
			this.up('form').getElements().each(function(e){
				if(!e.up('.contactType')) {
					if (e.id.indexOf('submit') == -1 && !e.match('input[type=hidden]')) {
						// Show fields for contact type, hide others
						if (displayFields.indexOf(e.id.substr(3)) != -1) {
							// If the row isn't shown, show it
							if(e.up('li').getStyle('display') == 'none') {
								new Effect.BlindDown(e.up('li'),{duration:0.25});
							}
						}
						else {
							e.value = "";	// Reset input value for hidden row
							// If the row isn't hidden, hide it
							if(e.up('li').getStyle('display') != 'none') {
								new Effect.BlindUp(e.up('li'),{duration:0.25});
							}
						}
						// Label appropriate required fields
						if (required.indexOf(e.id.substr(3)) != -1) {
							e.addClassName('required');
						} else {
							e.up('li').removeClassName('error');
							e.removeClassName('invalidFormField').removeClassName('required').removeClassName('error');
							if ($(e.identify() + "_error")) {
								$(e.identify() + "_error").remove();
							}
						}
					}
				}
			});
			var requiredElems = $$('#'+this.up('form').identify()+' input.required','#'+this.up('form').identify()+' textarea.required','#'+this.up('form').identify()+' select.required');
			validateForm(this.up('form').identify(), requiredElems, this.up('form').identify());
		});
	});

	$$('.applyType label').each(function(lbl){
		lbl.observe('mouseup',function(){
			switchForm(this);
		});
	});
	
	if($('apply_form')) {
		$$('.applyType label').each(function(e){
			if(e.down('input').checked == true) {
				switchForm(e);
			}
		});
	}

	if ($('tooltip')) {
		$('tooltip').fade({
			duration: 3.0,
			from: 0.0,
			to: 1.0
		});
	}
});


function switchForm(tElem) {
	// Row highlight interaction, assign selected class to parent row of label
	$(tElem).up('.applyType').descendants('li').each(function(e){
		if(e.hasClassName('selected')) {
			e.removeClassName('selected');
		}
	})
	$(tElem).up('li').addClassName('selected');
	
	// Set displayed and required fields for apllication type
	switch($(tElem).down('input').value) {
		case "publisher":
			var displayFields = new Array('email','name','phone','address','state','city','zip','website','category','visitors','pubagreement','tos','comments');
			var required = new Array('email','name','phone','address','state','city','zip','website','category','visitors','pubagreement','tos');
		break;
		case "advertiser":
			var displayFields = new Array('name','company','email','client','phone','spending','audience','comments');
			var required = new Array('name','company','email','client','phone','spending','audience');
		break;
	}
	
	$('id_required').value = required.join(",");
	$('id_visible').value = displayFields.join(",");
	
	// Parse through all inputs in the apllication form and 
	// modify according to selected application type
	$(tElem).up('form').getElements().each(function(e){
		if(!e.up('.applyType') && !e.match('input[type=hidden]')) {
			if (e.id.indexOf('submit') == -1) {
				// Show fields for apply type, hide others
				if (displayFields.indexOf(e.id.substr(3)) != -1) {
					// If the row isn't shown, show it
					if(e.up('li').getStyle('display') == 'none') {
						new Effect.BlindDown(e.up('li'),{duration:0.25});
					}
				}
				else {
					e.value = "";	// Reset input value for hidden row
					// If the row isn't hidden, hide it
					if(e.up('li').getStyle('display') != 'none') {
						new Effect.BlindUp(e.up('li'),{duration:0.25});
					}
				}
				// Label appropriate required fields
				if (required.indexOf(e.id.substr(3)) != -1) {
					e.addClassName('required');
				}
				else {
					e.up('li').removeClassName('error');
					e.removeClassName('invalidFormField').removeClassName('required').removeClassName('error');
					if ($(e.identify() + "_error")) {
						$(e.identify() + "_error").remove();
					}
				}
			}
		}
	});
	var requiredElems = $$('#'+$(tElem).up('form').identify()+' input.required','#'+$(tElem).up('form').identify()+' textarea.required','#'+$(tElem).up('form').identify()+' select.required');
	validateForm($(tElem).up('form').identify(), requiredElems, $(tElem).up('form').identify());
}


function runAdUnit(adUnitType,adURL,creativeURL,frameURL,continueURL) {
	if(continueURL == null) {
		continueURL = "";
	}
	if (!$('masker')) {
		var mask = document.createElement('DIV');
			document.body.appendChild(mask);
			$(mask).writeAttribute('id','masker').setStyle({
				position: 'absolute',
				zIndex: '10000',
				width: '100%',
				height: '100%',
				top: '0',
				left: '0',
				backgroundColor: '#000000',
				opacity: 0.0,
				display: 'none'
			});
	}

	switch(adUnitType) {
		case "video":
			adUnitWidth = 500;
			adUnitHeight = 370;
		break;
		case "billboard":
			adUnitWidth = 720;
			adUnitHeight = 307;
		break;
		case "medium-rectangle":
			adUnitWidth = 300;
			adUnitHeight = 257;
		break;
	}

	new Effect.Appear('masker',{
		duration:0.5,
		from:0,
		to:0.25,
		afterFinish: function(){
			var container = document.createElement('DIV');
				document.body.appendChild(container);
				$(container).writeAttribute('id','flashContainer').setStyle({
					position: 'absolute',
					top: document.viewport.getDimensions()['height']/2+document.viewport.getScrollOffsets()['top']+"px",
					left: '50%',
					marginLeft: '-'+(adUnitWidth/2)+'px',
					marginTop: '-'+(adUnitHeight/2)+'px',
					zIndex:'10001',
					width: (adUnitWidth+10)+'px',
					height: (adUnitHeight+26)+'px'
				})
			if(Prototype.Browser.IE) {
				imgSrc = "8bit";
			} else {
				imgSrc = "24bit";
			}
			$('flashContainer').setStyle({
				backgroundImage: 'url(images/'+adUnitType+'_ad-unit_back-'+imgSrc+'.png)'
			});

			$(container).update(
				'<div style="position:relative;padding:21px 5px 5px 5px;height:'+adUnitHeight+'px;width:'+adUnitWidth+'px;overflow:hidden;">'+
				'<object classid="clsid:d27cdb6e-ae6d-11cf-96b8-444553540000" codebase="http://download.macromedia.com/pub/shockwave/cabs/flash/swflash.cab#version=9,0,0,0" width="100%" height="100%" id="ad-unit" align="middle">'+
				'<param name="allowScriptAccess" value="sameDomain" />'+
				'<param name="allowFullScreen" value="false" />'+
				'<param name="movie" value="flash/'+adUnitType+'_ad-unit.swf?adURL='+adURL+'&creativeURL='+creativeURL+'&frameURL='+frameURL+'&continueURL='+continueURL+'" />'+
				'<param name="quality" value="best" />'+
				'<param name="bgcolor" value="#000000" />'+
				'<embed src="flash/'+adUnitType+'_ad-unit.swf?adURL='+adURL+'&creativeURL='+creativeURL+'&frameURL='+frameURL+'&continueURL='+continueURL+'"'+
				' quality="best"'+
				' bgcolor="#000000"'+
				' width="100%"'+
				' height="100%"'+
				' name="ad-unit"'+
				' align="middle"'+
				' allowScriptAccess="sameDomain"'+
				' allowFullScreen="false"'+
				' type="application/x-shockwave-flash"'+
				' pluginspage="http://www.macromedia.com/go/getflashplayer" />'+
				'</object>'
				+'</div>'
			);
		}
	});
}


function closeAdUnit() {
	$('flashContainer').remove();
	$('masker').remove();
	$(document.body).setStyle({overflow:'visible'});
}

function SelectAll(id){
    document.getElementById(id).focus();
    document.getElementById(id).select();
}
