var setupPage = {
	current: null,
	init: function() {
		this.testPane = $('test');
	},
	change: function() {
		var id = $F('whereTo');
		var newSection = id == '' ? null : $(id);
		if (newSection != this.current) {
			if (null !== this.current) {this.current.hide();}
			if (null !== newSection) {newSection.show();}
			this.current = newSection;
		}
	},
	checkLandingPageAgain: function(jobId, token) {
		var url = '"<%= url_for :action => :check_medallion, :id => @site.id %>?job=' + jobId + '&authenticity_token=' + token + '"';
		setTimeout('new Ajax.Request(' + url + ')', 700);
	},
	startTest: function() {
		if (null === this.spinner) {this.spinner = new Spinner('urlTesterSpinner');}
		this.spinner.startAndDisable('testURL');
		var dnn = new Ajax.Request('<%= url_for :action => :check_medallion, :id => @site.id %>', { asynchronous:true, evalScripts:true, parameters:Form.serialize($('url').up('form'))});
	},
	testComplete: function() {
		this.spinner.stop();
	}
};

// need this for medallion verification function
var startUrl = 'nottested';

function onVLClick(e)
{
  if(e.element().hasClassName('current')) {
    return;
  }
	// this should be the ID of the clicked element, less the first two chars
	var el = e.element().identify().substr(2);
  // removes the current class from previous selection
	$$('.video-list .current, .video-box .current').each(function(item) {
	  item.removeClassName('current');
	})
  // adds current class to new selection
	$(el).addClassName('current');
	$('l-'+el).addClassName('current');

	e.stop();
}

// revised dom:loaded function
document.observe('dom:loaded', function() {
  // set up click observors for video links
  if($$('.video-link')) {
    $$('.video-link').each(function(item) {
      item.observe('click', onVLClick);
    });
  }
	
  // Manage sorting, directionality, per page count and filtering list pages such as All Sites, My Sites
	if($('listSorter'))
	{
		Event.observe($('order'), 'change',
			function(e)
			{
				$('listSorter').submit();
				e.stop();
			}
		);
		Event.observe($('direction'), 'change',
			function(e)
			{
				$('listSorter').submit();
				e.stop();
			}
		);
		Event.observe($('items_per_page'), 'change',
			function(e)
			{
				$('listSorter').submit();
				e.stop();
			}
		);
		Event.observe($('name_filter'), 'change',
			function(e)
			{
				$('listSorter').submit();
				e.stop();
			}
		);
	}

  // Add Clear Filter link when user enters a filter for a list page 
  // (e.g., All Sites)
	if($('name_filter_none')) {
	  $('name_filter_none').observe('change', function(e) {
      // alert('here');
	    if($F('name_filter') != '') {
		    var ncf = new Element('a');
		    ncf.update('Clear Filter');
		    ncf.writeAttribute('href', '');
		    $('needs_clear_filter').update(ncf);
		    $('needs_clear_filter').setStyle({marginTop: '6px'})
		    $('name_filter').insert({'after': ncd});
	    }
    });
	}

  // Force user to confirm navigating away from Add/Manage Site page without verifying medallion first
  if($('getMedallionCode')) {
    if( $F('verifiedURL') == 'false') {
      // startUrl is set up top, before dom:loaded block begins
      if(startUrl == 'nottested') {
        startUrl = $F('site_url');
      }
      window.onbeforeunload = function() {
        // did user update the url? then don't confirm.
        if(startUrl != $F('site_url')) {
          return
        }
        if( false && $$('.trackingOff').size() ) {
          return "You have not verified your medallion, a step required for activation. You can return later by clicking the Manage button for this site.\n\nDo you still wish to leave?";
        }
      };
    }
  }

  if($('addSiteForm')) {
	$('addSiteForm').select('input[type=submit]').invoke('observe', 'click', function(e) {
		if(this.id == 'cancel_site_add') {
			// if any of the key fields are filled in, confirm the want-away
			if(($('site_name').present()) || ($F('site_url').present()) || ($F('site_email').present())) {
				var r = confirm("Please confirm you wish to leave with an unsaved Site");
				if(r === false) {
					Event.stop(e);
				}
			}
		}
	});
  }
	
  // Manage paging for list pages such as All Sites, My Sites
	function listPager(e) {
		var el = e.element();
		if (el.match('.pagination a')) {
			// el.up('.pagination').insert(createSpinner());
			// var nar = new Ajax.Request(el.href, { method: 'get' });
			var nar = new Ajax.Request(el.href + "?order=" + $F('order') + "&dir=" + $F('direction') + "&per_page=" + $F('items_per_page') + "&page=" + $F('cur_page') + nfs, {method: 'get'});
			e.stop();
		}
	}

	if($('listPaginator_none')) {
		$('listPaginator').observe('click', listPager);
	}

  // User wants Activation email resent
	if($('update-thank-you-email')) {
		Event.observe($('update-thank-you-email'), 'click', function() {
			$('user_email').up('form').submit();
			return false;
		});
	}
	
	// For getting platform-specific Medallion code
	function selectMedTarget(e) {
		var id = $F('');
		var newSection = id == '' ? null : $(id);
		if (newSection != this.current) {
			if (null !== this.current) {this.current.hide();}
			if (null !== newSection) {newSection.show();}
			if (null === newSection) {
				this.testPane.hide();
			} else {
				this.testPane.show();
			}
			this.current = newSection;
		}
	}
	
	function setupBrowserStyles() {
		var body = $(document.body);
		if (Prototype.Browser.IE) {
			body.addClassName('IE');
		}
		if (Prototype.Browser.Gecko) {
			body.addClassName('Gecko');
		}
		if (Prototype.Browser.WebKit) {
			body.addClassName('WebKit');
		}
		if (Prototype.Browser.MobileSafari) {
			body.addClassName('MobileSafari');
		}
		if (Prototype.Browser.Opera) {
			body.addClassName('Opera');
		}
	}

	// Added browser css classes for easy styling
	setupBrowserStyles();

  // Turn on observer for platform-specific medallion code
	if($('whereTo')) {
		document.observe('dom:loaded', function() { setupPage.init(); });
		$('whereTo').observe('change', selectMedTarget);
	}
	
});

// This var + function manage toggling the Login box
// as well as looking for clicks when its visible
var observing = false;
function toggleLoginBox() {
	if($('login-box').visible()) {
		if(observing) {
			$(document.body).stopObserving('click');
			observing = false;
		}
		$('loginLink').ancestors()[0].setStyle({backgroundColor: 'transparent'});
		$("login-box").hide();
	} else {
		$('loginLink').ancestors()[0].setStyle({backgroundColor: '#eff7f7'});
		$("login-box").show();
		observing = true;
		// Observer for clicks when Login box visible
		// Has to distinguish whether click is outside box
		Event.observe(document.body, 'click', function(event) {
			var elm = event.element();
			var shouldLeave = false;
			shouldLeave = (elm == $('login-box') || elm.hasClassName('in-login-box') || (elm == $('loginLink')) || elm.hasClassName('loginLinkContainer'));
			if(shouldLeave) {
				Event.stop(event);
				return false;
			}
			toggleLoginBox();
		});
	}
}

// var Utils = {
//	redirectTo: function(url) {
//		window.location.href = url;
//	},
//	now: function() {
//		return new Date();
//	},
//	centerInWindow: function(element) {
//		this.alignInWindow(element, 0.5, 0.33);
//	},
//	alignInWindow: function(element, horizontalRatio, verticalRatio) {
//		var windowDimensions = Utils.windowDimensions();
//		var elementDimensions = Element.getDimensions(element);
// 
//		var new_left = (windowDimensions.width - elementDimensions.width) * horizontalRatio + "px";
//		var new_top = (windowDimensions.height - elementDimensions.height) * verticalRatio + "px";
//		element.style.left = new_left;
//		element.style.top = new_top;
//	},
//	 windowDimensions: function() {
//		return {
//			height: this.window().innerHeight || document.body.clientHeight,
//			width: this.window().innerWidth || document.body.clientWidth;
//		}
//	 },
//	useMockWindow: function (w) {
//		this.mockedWindow = w;
//	},
//	window: function() {
//		return this.mockedWindow || window;
//	},
//	redirectIfConfirm: function(msg, url) {
//		if (confirm(msg)) {this.redirectTo(url);}
//	},
//	closeFlash: function() {
//	Effect.SlideUp('flash');
//	},
//	setFlash: function(text) {
//	var flash = $('flash');
//	var span = flash.down('span');
//	span.innerHTML = text;
//	Effect.SlideDown(flash);	
//	},
//	submitFormIfValid: function(formId) {
//		var form = $(formId);
//		if (LiveValidation.massValidate(LiveValidationForm.getInstance(form).fields)) {
//			form.submit();
//		}
//	},
//	 // insertAddress: function(name) {
//	 //	domain ="kachingle";
//	 //	extension = "com";
//	 //	emailAdd=(name + '@' + domain + '.' + extension);
//	 //	document.write('<a href="mailto:' + emailAdd + '">' + emailAdd + '</a>');
//	 // },
//	confirm: function(url, question) {
//		if (question === null) { question = "Are you sure?"; }
//		var answer = confirm(question);
//		if (answer) { window.location = url; }
//	}
// };

// var MenuBarHandler = Class.create();
// MenuBarHandler.prototype = {
//	initialize: function(dfltMenu) {
//		document.observe("dom:loaded", this.domLoaded.bindAsEventListener(this));
//		this.dfltMenu = this.onMenu = dfltMenu;
//	},
//	domLoaded: function() {
//		var menus = $('navCircle');
//		for (var i = 0; i < 999; ++i) {
//			var li = menus.down('li', i);
//			if (null === li) {
//				break;
//			}
//			if (0 === li.id.indexOf("menu")) {
//				li.onmouseover = this.overMenu.bindAsEventListener(this, li.id);
//				li.onmouseout = this.offMenu.bindAsEventListener(this);
//			}
//		}
//	},
//	overMenu: function(e, label) {
//		this.displaySubMenu(label);
//	},
//	offMenu: function(e) {
//		this.displaySubMenu(this.dfltMenu);
//	},
//	displaySubMenu: function(menu) {
//		if (menu == this.onMenu) {
//			return;
//		}
//		Element.hide('sub' + this.onMenu);
//		Element.show('sub' + menu);
//		this.onMenu = menu;
//	}
// };

var Spinner = Class.create();

Spinner.prototype = {
	initialize: function(spinnerID) {
		if (null === spinnerID) {spinnerID = 'spinner';} //	Default value
		this.spinner = $(spinnerID);
	},
	start: function() {
		Element.show(this.spinner);
	},
	startAndDisable: function(button2Disable) {
		if (null === button2Disable) {button2Disable = 'submit';}
		this.disabledButton = $(button2Disable);
		this.disabledButton.disabled = true;
		this.start();
	},
	stop: function() {
		Element.hide(this.spinner);
		if (null !== this.disabledButton) {this.disabledButton.disabled = false;}
		this.disabledButton = null;
	}
};

// var ButtonHandler = Class.create();
// 
// ButtonHandler.prototype = {
//	initialize: function(id, onClickFunction) {
//		this.elem = $(id);
//		this.onClickFunction = eval("this." + onClickFunction + ".bind(this)");
//		this.elem.onclick = this.onClick.bindAsEventListener(this);
//	},
//	onClick: function(elem) {
//		this.onClickFunction();
//	},
//	submitEnclosingFormIfValid: function() {
//		if (this.elem.hasClassName('disabled')) return;
//		var form = this.elem.up('form');
//		if (null == form) return;
//		var formValidator = LiveValidationForm.getInstance(form);
//		if (null == formValidator) return;
//		if (LiveValidation.massValidate(formValidator.fields)) {
//			this.elem.addClassName('disabled');
//			form.submit();
//		}
//	},
//	submitEnclosingForm: function() {
//		if (this.elem.hasClassName('disabled')) return;
//		var form = this.elem.up('form');
//		if (null == form) return;
//		this.elem.addClassName('disabled');
//		form.submit();
//	}
// }


/**
 * Styling File Inputs - AKA 'FileUI'
 * @author: Marc Grabanski
 * @sdoc: http://marcgrabanski.com/code/style-file-input
 */
var FileUI = {
	disableText : false,
	imgPath : '/images/browse.gif',
	imgPathOver : null,
	textOnly : null,
	spanClass : 'fileInput',
	
	init : function () 
	{
		var spans = document.getElementsByTagName('span');
		for (var i = 0; i < spans.length; i++)
		{
			if (spans[i].className.indexOf(this.spanClass) != -1)
			{
				this.style( spans[i], spans[i].getElementsByTagName('input')[0] );
			}
		}
	},
	style : function (span, input)
	{
		setStyle = (navigator.appVersion.indexOf("MSIE")!=-1) ? 'cssText' : 'style';
		this.setStyle(span, 'position:relative;border:1px solid transparent;');
		this.setStyle(input, 'width:260px;position:absolute;top:0;left:0;z-index:5;-moz-opacity:0;filter:alpha(opacity:0);opacity:0;');
		
		var txtInput = document.createElement('input');
		txtInputWidth = 180;
		txtInput.type = 'text';
		this.setStyle(txtInput, 
			'width:' + txtInputWidth + 'px;position:absolute;top:0px;left:0px;z-index:10');
		input.onchange = function () {
			txtInput.value = input.value;
		};
		txtInput.disabled = 'disabled';
		span.appendChild(txtInput);
		
		var link = document.createElement('a');
		linkLeft = txtInputWidth + 8;
		this.setStyle(link, 'position:absolute;top:0px;left:' + linkLeft + 'px;');
		if (this.textOnly === null) {
			var img = document.createElement('img');
			img.src = this.imgPath;
			link.appendChild(img);
			if (this.imgPathOver !== null) {
				input.onmouseover = function () { img.src = FileUI.imgPathOver; };
				input.onmouseout = function () { img.src = FileUI.imgPath; };
			}
		} else {
			link.innerHTML = this.textOnly;
			link.href = "#";
			link.onclick = function () { return false; };
			input.onmouseover = function () { link.className = 'over'; };
			input.onmouseout = function () { link.className = ''; };
		}
		span.appendChild(link);
	},
	setStyle : function (object, styleText) { 
		if( object.style.setAttribute ) { object.style.setAttribute("cssText", styleText ); } 
		else { object.setAttribute("style", styleText ); } 
	}
};
