function setLoginSubmit()
{
	if(document.getElementById("passwordChoice2").checked == true)
	{
		document.getElementById("passwordText").focus();
		document.getElementById("loginButton").value = "Login";
	}
	else
	{
		document.getElementById("loginButton").value = "Continue";
	}
}

function setLoginRadio(val)
{
	document.getElementById("passwordChoice2").checked = "checked";
	setLoginSubmit()
}

Object.extend(Element, {
	getBehaviourProperty: function(element, attribute) {
		if(element.getAttribute('properties'))
			var properties = element.getAttribute('properties').split(", ");
		else
			return false;
		var result = properties.detect(function(item) {return item.indexOf(attribute) == 0;});
		if(result)
			return result = result.split(attribute + ":")[1];
		else
			return false;
	},
	addBehaviourProperty: function(element, attribute, value) {
		var properties = element.getAttribute('properties');
		if(properties)
			element.setAttribute("properties", properties + ", " + attribute + ":" + value);
		else
			element.setAttribute("properties", attribute + ":" + value);
	}
});

var Behaviour = Class.create();
Behaviour.prototype = {
  initialize: function(selector, observers) {
		$$(selector).each(function(el){
				observers.each(function(observer){
				var event = observer[0], handler = observer[1];
					if(event == 'load')
						handler(el);
					else
						Event.observe(el, event, handler, false);	
				});
		});
  }
}

function debug(aMsg) {
   setTimeout(function() { throw new Error("[debug] " + aMsg); }, 0);
}

function init(){
  loadBehaviours.each(function(el){
  	eval(el);
  });
}

var loadBehaviours = [];


function setPasswordAndRadio(radio,password)
{
	document.getElementById(radio).checked = true;
	if(document.getElementById(password).value == "")
	{
		document.getElementById(password).focus();
	}
}

function setLoginText(val)
{
	
	if(val != "")
	{
		document.getElementById("loginButton").value = "Login";
	}
	else
	{
		document.getElementById("loginButton").value = "Continue";
	
	}
}

function setLoginSubmit()
{
	if(document.getElementById("passwordChoice2").checked == true)
	{
		document.getElementById("passwordText").focus();
		document.getElementById("loginButton").value = "Login";
	}
	else
	{
		document.getElementById("loginButton").value = "Continue";
	}
}

function setLoginRadio(val)
{
	document.getElementById("passwordChoice2").checked = "checked";
	setLoginSubmit()
}

function rate(rating, seq, artworkId, status, school, tag, maxArtworks)
{
	var formRating = document.getElementById('site/rateArtwork.rating');
	formRating.value = rating;
	nextArtwork(seq, rating, artworkId, status, school, tag, maxArtworks);
}

function focusKeyword() {$('site/rateArtwork.judgeKeywords').focus();}

function nextArtwork(seq, rating, artworkId, statusId, schoolId, tag, maxArtworks)
{
	//alert(seq + "," + rating + "," + artworkId + "," + statusId + "," + schoolId + "," + tag + "," + maxArtworks);
	var judgeKeywords = document.getElementById('site/rateArtwork.judgeKeywords');
	var bodyClassName = document.getElementById('body').className;
	
	var params = '';
	var link = '/text-only/ajax/request.html';
	params += "template=/site/templates/ajax/view-judging-artwork.vm";
	if(rating == statusId) // not changing status so view next artwork
		params += "&seqNo="+(++seq);
	else params += "&seqNo="+(seq); // status change so stay on same seq number to view the next artwork (as current artwork has different status and
									// so is no longer displayed
	
	//alert(seq);
	
	params += "&action=com.othermedia.royalacademy.summerexhibition.actions.SummerExhibitionSaveActions.doDefault";
	params += "&statusId="+(statusId);
	params += "&schoolId="+(schoolId);
	params += "&tag="+(tag);
	params += "&rating="+(rating);
	params += "&judgeKeywords="+(judgeKeywords.value);
	params += "&artworkId="+(artworkId);
	params += "&bgColour="+(bodyClassName);
	params += "&direction=next";
	params += "&maxArtworks="+(maxArtworks);
	new Ajax.Updater('JudgeArtwork', link, { parameters:params, onComplete: focusKeyword, evalScripts: true });
}
function prevArtwork(seq, rating, artworkId, statusId, schoolId, tag)
{
	var judgeKeywords = document.getElementById('site/rateArtwork.judgeKeywords');
	var bodyClassName = document.getElementById('body').className;
	var params = '';
	var link = '/text-only/ajax/request.html';
	params += "template=/site/templates/ajax/view-judging-artwork.vm";
	params += "&seqNo="+(--seq);
	params += "&action=com.othermedia.royalacademy.summerexhibition.actions.SummerExhibitionSaveActions.doDefault";
	params += "&statusId="+(statusId);
	params += "&schoolId="+(schoolId);
	params += "&tag="+(tag);
	params += "&rating="+(rating);
	params += "&judgeKeywords="+(judgeKeywords.value);
	params += "&artworkId="+(artworkId);
	params += "&bgColour="+(bodyClassName);
    params += "&direction=prev";
	new Ajax.Updater('JudgeArtwork', link, { parameters:params, onComplete: focusKeyword, evalScripts: true });
}

function highlight(target)
{
	var t = $(target);
	t.addClassName('highlight');
}

function lowlight(target)
{
	var t = $(target);
	t.removeClassName('highlight');
}

function showinfo()
{
	$('info').show();
}

function hideinfo()
{
	$('info').hide();
}
function showhelp()
{
	$('help').show();
}

function hidehelp()
{
	$('help').hide();
}

function showMainImage(image,max)
{
	removeAllMain(max);
	var option = document.getElementById(image);
	option.style.display = "block";
}
function removeAllMain(max)
{
	var image1 = document.getElementById('LargeImageOne');
    image1.style.display = "none";
	var image2 = document.getElementById('LargeImageTwo');
    image2.style.display = "none";
	var image3 = document.getElementById('LargeImageThree');
	image3.style.display = "none";	
}



function newWindow(e){
	var title = Element.getBehaviourProperty(e,'linkTitle');
	e.target = "_blank";
	e.title = title ? title : "This link opens in a new window";
}

loadBehaviours[loadBehaviours.length] = "new Behaviour('A.new-window', [['load',newWindow]])";



function popupWindow(e){
	var title = Element.getBehaviourProperty(e,'linkTitle');
	e.target = "popupWindow";
	e.title = title ? title : "This link opens in a popup window";
}

function popupOpen(e) {
	//e = Event.findElement(Event.element(e), "A");
	var w = Element.getBehaviourProperty(Event.element(e),'popupWidth'), h = Element.getBehaviourProperty(Event.element(e),'popupHeight');
	if(!w||!h)
		{w=600; h=500;}
	var popup = window.open('', 'popupWindow','resizable=1,location=1,scrollbars=1,status=1,top=' + Math.round(document.body.clientHeight/2 - h/2) + ',left=' + Math.round(document.body.clientWidth/2 - w/2) + ',width=' + w + ',height=' + h);
}

loadBehaviours[loadBehaviours.length] = "new Behaviour('A.popup-window', [['load',popupWindow], ['click',popupOpen]])";



function addHover(e){Element.addClassName(Event.element(e), 'hover');}

function removeHover(e){Element.removeClassName(Event.element(e), 'hover');}

loadBehaviours[loadBehaviours.length] = "new Behaviour('.rollover', [['mouseover',addHover], ['mouseout',removeHover]])";


function setTabs(e) {
	$$("#" + e.id + " DIV.tab").each(function(tab, index){
			if(checkParentTab(tab,e)) {
					Element.addBehaviourProperty(tab, 'tabGroup' , e.id);
					Element.addBehaviourProperty(tab, 'tabIndex' , index);
					Event.observe(tab, 'click', switchTab, false);
			}
	});

	$$("#" + e.id + " DIV.block").each(function(block, index){
			if(checkParentTab(block,e)) {
					Element.addBehaviourProperty(block, 'tabGroup' , e.id);
					Element.addBehaviourProperty(block, 'tabIndex' , index);
			}
	})
}

function switchTab(e) {

	e = Event.findElement(e, "DIV");

	var group = Element.getBehaviourProperty(e,'tabGroup'), index = Element.getBehaviourProperty(e,'tabIndex');
	$$("#" + group + " DIV.tab").each(function(el){
		if(checkParentTab(el,$(group)))
					Element.removeClassName(el, 'tab-shown');
	})
	Element.addClassName(e, 'tab-shown');
	$$("#" + group + " DIV.block").each(function(el){
		if(checkParentTab(el,$(group))) {
			if(Element.getBehaviourProperty(el,'tabIndex') == index)
				Element.addClassName(el, 'block-shown');
			else
				Element.removeClassName(el, 'block-shown');
		}
	})
}

function checkParentTab(element,parent) {
  var e = element;
  while (e != parent){
  	if (Element.hasClassName(e, 'tabs'))
				return false;
		e = e.parentNode;
  }
	return true;
}

loadBehaviours[loadBehaviours.length] = "new Behaviour('DIV.tabs', [['load',setTabs]])";



function updateAjax(e) {
	var id = $(Element.getBehaviourProperty(Event.element(e),'ajaxId')), url = Element.getBehaviourProperty(Event.element(e),'ajaxUrl');
	Element.addClassName(id, 'updating');
	new Ajax.Updater(id, url, {onSuccess : function() {Element.removeClassName(id, 'updating');}});
}

function periodicAjax(e) {
    Ajax.Responders.register({onCreate:showLoader, onComplete:hideLoader});
	var selector = Element.getBehaviourProperty(e,'ajaxUpdateSelector'), interval = Element.getBehaviourProperty(e,'ajaxInterval');
	interval = interval ? interval :30;
    new PeriodicalExecuter(function(){
    	$$(selector).each(function(el){
    		var id = Element.getBehaviourProperty(el,'ajaxId'), url = Element.getBehaviourProperty(el,'ajaxUrl');
    		new Ajax.Updater($(id), url);
    	});
    }, interval);
}

function showLoader() {
	$$(".ajax-global-spinner").each(function(el){
		Element.addClassName(el, 'global-spinning');
	});
}

function hideLoader() {
	$$(".ajax-global-spinner").each(function(el){
		Element.removeClassName(el, 'global-spinning');
	});
}
loadBehaviours[loadBehaviours.length] = "new Behaviour('.update-ajax', [['click',updateAjax]])";
loadBehaviours[loadBehaviours.length] = "new Behaviour('.periodic-ajax', [['load',periodicAjax]])";




function setLabelShift(e) {Element.addClassName(e, 'label-shift');}

function hideLabel(e) {
	$$("DIV.search LABEL").each(function(l, index){
		Element.addClassName(l, 'hide-label');
	});
}

function showLabel(e) {
	$$("DIV.search LABEL").each(function(l, index){
		if($(l.getAttribute("for")).value == "")
			Element.removeClassName(l, 'hide-label');
	}); 
}

loadBehaviours[loadBehaviours.length] = "new Behaviour('DIV.search LABEL', [['load',setLabelShift], ['click',hideLabel]])";
loadBehaviours[loadBehaviours.length] = "new Behaviour('DIV.search .text', [['focus',hideLabel], ['blur',showLabel], ['click',hideLabel]])";



function toggleActivate(e) {
	$$(Element.getBehaviourProperty(Event.element(e),'toggleSelector')).each(function(el, index){
		if(Element.hasClassName(el, 'toggle-active')) {
			Element.removeClassName(Event.element(e), 'toggle-button-on');
			Event.element(e).innerHTML = "Show photo credits";
			Element.removeClassName(el, 'toggle-active');
			
		} else {
			Element.addClassName(Event.element(e), 'toggle-button-on');
			Event.element(e).innerHTML = "Hide photo credits";
			Element.addClassName(el, 'toggle-active');
		}
	});
}

loadBehaviours[loadBehaviours.length] = "new Behaviour('.toggle-button', [['click',toggleActivate]])";




function activateElement(e) {
	$$(Element.getBehaviourProperty(Event.element(e),'activateSelector')).each(function(el, index){
		if(el.tagName == "INPUT") {
			if(el.type == "radio" || el.type == "checkbox") el.checked = true;
			if(el.type == "text" || el.type == "password") el.focus();
		}
		if(el.tagName == "TEXTAREA") el.focus();
	});
}

loadBehaviours[loadBehaviours.length] = "new Behaviour('.activate-element', [['click',activateElement], ['focus',activateElement]])";

function deActivateElement(e) {
	$$(Element.getBehaviourProperty(Event.element(e),'deActivateSelector')).each(function(el, index){
		if(el.tagName == "INPUT") {
			if(el.type == "radio" || el.type == "checkbox") el.checked = false;
			if(el.type == "text" || el.type == "password") el.value = "";
		}
		if(el.tagName == "TEXTAREA") el.value = "";
	});
}

loadBehaviours[loadBehaviours.length] = "new Behaviour('.deactivate-element', [['click',deActivateElement], ['focus',deActivateElement]])";

function addToBasket(url)
{
	var opt = {
	    // Use GET
	    method: 'get',
	    
	    // Handle successful response
	    onSuccess: function(t) {
	        Element.update("BasketWrapper", t.responseText);
	        Droppables.add('Basket',{onDrop: basketOnDrop,hoverclass:'basket-hover'});
	        new Effect.Highlight("Basket",{startcolor:'#FFFF66'});
	        
	    },
	    
	    // Handle 404
	    on404: function(t) {
	    //    alert('Error 404: location "' + t.statusText + '" was not found.');
	    },
	    
	    // Handle other errors
	    onFailure: function(t) {
	        alert('Error ' + t.status + ' -- ' + t.statusText);
	    }
	}
	new Ajax.Request(url, opt);
}

function updateColourBar(url)
{
	var opt = {
	    // Use GET
	    method: 'get',
	    
	    // Handle successful response
	    onSuccess: function(t) {
	        Element.update("colourbarWrapper", t.responseText);
	        new Effect.Highlight("colourbar",{startcolor:'#FFFF66'});
	    },
	    
	    // Handle 404
	    on404: function(t) {
	    //    alert('Error 404: location "' + t.statusText + '" was not found.');
	    },
	    
	    // Handle other errors
	    onFailure: function(t) {
	        alert('Error ' + t.status + ' -- ' + t.statusText);
	    }
	}
	new Ajax.Request(url, opt);
}

function basketOnDrop(element) 
 { 
 	elementId = element.id;
	linkId = elementId.replace(/Thumbnail-/,"BuyLink-"); 
	prodHref = $(linkId).getAttribute('href');
	url = prodHref.replace(/javascript:addToBasket\('(.*)'\)/,"$1");
	url = url.replace(/actionToken=(\w|-)*&/, "");
	addToBasket(url);
}






window.onload = init;

Event.observe(window, 'load', function() {
    var elements = $$('a input');
    elements.each(function(el) {
        el.observe('focus', function(e) { el.addClassName('focus'); });
        el.observe('blur', function(e) { el.removeClassName('focus'); });
    });
});
