//////////////////////////////////////////////////////////////////////////////////// BIOS PUB SCRIPTS
//////////////////////////////////////////////////////////////////////////////////// LANG
var lang = "";
var slides = "";
var ticker = "";
var state = "thumb";
var arrThumbs = [];

// Translation lang switch
// Adds unOb js to lang translate buttons
function initTranslator() {
	$$(".translate li").each(function(li) {
		//li.set("href","");
		// init translator
		li.addEvent('click', function(event){
			translate(li.get('id'));
		}, this);
		// stop the event firing
		li.getElements("a").addEvent('click', function(event){
			//alert("clicked");
			event.preventDefault();
		}, this);
	});
	checkTranslatorLang();
}


// reads cookie on user system to see if lang is set - if no defaults to EL
function checkTranslatorLang() {
	//alert(Cookie.read("lang")==null);
	try {
	//if (Cookie.read("lang") == 'undefined' || Cookie.read("lang") == null || Cookie.read("lang") == 'null') {
	if (Cookie.read("lang")==null) {
		lang = "el";
		//alert(1);
	} else {
		lang = Cookie.read("lang");
		//alert(2);
	}
	} catch (e) { alert(e);}
	//alert(lang);
	translate(lang);
}


// switches the site lang and sets cookie in users browser to set their lang choice
function translate(lang) {
	//alert(lang);
	showLang = "."+lang;
	switch (lang) {
	case "en":
		$("el").removeClass("on");
		hideLang = ".el";
		break;
	case "el":
		hideLang = ".en";
		$("en").removeClass("on");
	break;
	}
	$$(showLang).each(function(copy) {
		copy.show();
	}, this);
	$$(hideLang).each(function(copy) {
		copy.hide();
	}, this);
	
	// set lang for each thumb
	arrThumbs.each(function(biosTn) { biosTn.setLang(lang); biosTn.switchView(state); });
	
	// cleanup - set cookie to lang + set lang button to on
	Cookie.write("lang", lang);
	$(lang).addClass("on");
	//css = new Asset.css('/inc/css/pub.lang.css.php?lang='+lang, { media:'screen'});
}


// applies events to all document lists for rollovers, clicks and styling
function setDlEvents() {
	$$("dl").each(function(dl) { var dlRoll = new DlRollOver(dl); })
}


function search() {
	$("search-form").getElement("from").set("value", $("date_from").get("value"));
	document.forms['search-form'].submit();
}


function checkEvent() {
	
}


function setupTicker() {
	$("ticker").position({
		position: 'topLeft',
		edge: 'topLeft',
		relativeTo: $("hdr"),
		offset: {x:40, y:194}
	});	
}


function slideShow() {
	//alert('yo');
	try {
		ticker = new SimpleSlideShow.Carousel($("tickerC"), {
		startIndex: 0,
		slides: $$('#tickerC .tickerContent')
		});

		slides = new SimpleImageSlideShow($('featured'), {
			startIndex: 0,
			slides: $$('div#featured a img')
		});

		// init animation using slideshow assets
		ani = new Animation({delay:5000, slideShow:slides, tickerShow:ticker}).go();
	} catch (e) { alert(e) }
}


function gallerySlides() {
	$$(".biosTn").each(function(gallery) { 
		var gId = gallery.get('id');
		//alert(gId);
		slides = new SimpleImageSlideShow(gallery, {
		  startIndex: 0,
		  slides: $$('div#'+gId+' a img')
		});
		var intDelay = ($random(4, 10))*1000;
		//alert(intDelay);
		// init animation using slideshow assets
		ani = new Animation({delay:intDelay, slideShow:slides}).go();
	}, this)
}


// custom class to animate slideshow based on delay
Animation = new Class({
	Implements:[Chain,Options],
	options: {
		delay: 2000,
		slideShow: null,
		tickerShow: null
	},
	initialize: function(options){
		// set options
		this.setOptions(options);
		//alert(this.options.slideShow);
  },
  
	go: function(tId){
	  var self = this;
		this.chain(
			function(){this.next.delay(this.options.delay,this);}
		);
		this.callChain()
	},
	next:function() {
		//alert(slides);
		this.options.slideShow.forward();
		if (this.options.tickerShow) { this.options.tickerShow.forward(); }
		this.go();
	}
});


//////////////////////////////////////////////////////////////////////////////////// AJAX
// Global ajax handler
function ajaxMgr() {
	var args = ajaxMgr.arguments;
	ajaxPath = '/inc/php/ajax/';
	//alert(1);
	switch (args[0]) {
	case "GET":
		var url = ajaxPath+args[1];
		var qString = args[2];
		new Request({method: 'get'}).send(url+"?"+qString);
		break;
	case "SEND":
		var url = ajaxPath+args[1];
		var qString = args[2];
		//alert(url);
		var req = new Request({
			url: url,
			onComplete: function(response){ 
				//alert(response);
				var arr = response.split('|');
				//alert(arr);
				var bg = arr[0];
				var col = arr[1];
				//alert(bg+' '+col);
				var body = $(document.body);
				//alert(body);
				body.getStyle('background-color');
				body.setStyle('background-image',"/img/bg/"+bg );
				body.setStyle('background-color',col );
			}
		});
		req.send(qString);
		break;		
	case "HTML":
		var url = ajaxPath+args[1];
		var req = new Request.HTML({
			url:ajaxPath+args[1],
			update:args[3],
			onComplete: function(response){ setStatus(); }
		});
		//req.addEvent('complete', closeRequest);
		req.send(args[2]);	
		break;
	default :
		alert ( 'ajaxMgr: ERROR - case not suplied for '+args[0] );
		break;		
  }
}


// Ajax Functions
function calendarDateCallback(strDate) {
	ajaxMgr("HTML","getEventsByDate.php", "str_date="+strDate, "GHCalendarEvents");
}


function subscribe() {
	//$('list').set('html', 'Please Wait');
	ajaxMgr("HTML","subscribeToList.php", "str_email="+$('str_email_address').get('value'), "list");
}


function getRandomBg() {
	ajaxMgr("SEND","getRandomBg.php", null, "galleryImages");
}


function closeRequest(){
	document.close();
	//alert(1);
	setStatus();
}


function fadeThumbs() {
	$$('.galleryImages').each(function(container) {
		container.getChildren().each(function(child) {
			var siblings = child.getParent().getChildren().erase(child);
			siblings.set('tween', {duration: 50});
			child.addEvents({
				mouseenter: function() { siblings.tween('opacity',0.3); },
				mouseleave: function() { siblings.tween('opacity',1); }
			});
		});
	});
}


function setStatus() {
	//window.status="bios.      exploring urban culture";
	checkTranslatorLang();
	$$("#GHCalendarEvents dl").each(function(dl) { var dlRoll = new DlRollOver(dl); })
	//checkEventList();
	//alert("yo");
}


// add unOb js to subscribeLink
function setupSubscribeLink(){
	var el = $("subscribeBut");
	el.set("href","javascript:subscribe();");
}



// copes with required fields in forms - loops through forms on page and checks form id
// if form id match case statement add form check object to form related to id
function setupForms() {
	//alert("forms");
	$$("form").each(function(form) {
		switch (form.id) {
		case "subscribe":
			setupSubscribeLink();
			new FormCheck(form.id, {
				display : {
					tipsPosition: "left",
					indicateErrors : 1,
					showErrors: 0,
					tipsOffsetX:-20
				}
			});
		}
	});
}


function alignCalendar() {
	if ($("GHCalendarEvents")) {
		var cal = $("GHCalendarEvents");
		var el = $("right");
		cal.position({
			position: 'topRight',
			edge: 'topLeft',
			relativeTo: el,
			offset: {x:3, y:-18}
		});
	}
	//cal.setStyle("padding-top", "0px");
}


// regular expression to replace values
function replVal(value,str2Repl,replStr) {
	str2Repl = new String (str2Repl);
	//alert(str2Repl +' '+replStr);
	rExp = new RegExp(str2Repl, "gi");
	replStr = new String(replStr);
	return value.replace(rExp, replStr);
}


// adds overtext to all fields with a class name of overtext
function setupOverText() {
	//alert(1);
	$$(".overText").each(function(field) {
		//alert($(field.get('id')));
		field.set("alt", field.get("value"));
		field.set("value", '');
		new OverText($(field.get('id')));
	});
}


function pinMenu() {
	if(Browser.Engine.trident){
		//alert(Browser.Engine.version)
		if (Browser.Engine.version == 4 ){
			$("logo").setStyle("position", "absolute");
			Browser.fixPNG($("logo"));
		}
	}
	$("logo").addEvents({
		mouseover: function(logo){
			this.addClass("hover");
		},
		mouseout: function(logo){
			this.removeClass("hover");
		},
		click: function(){
			if ($("container").hasClass("biosShop")) {
				document.location.href= "/shop/";
			} else {
				document.location.href= "/";
			}
		}
	}, this);
}


// sets up the events rollovers
function setupBiosList() {
	$$(".biosTn").each(function(biosTn) { var tnRoll = new ImgDivRollOverLang(biosTn); arrThumbs.include(tnRoll); })
}


function setupCopy() {
	$$(".copy").each(function(det) {
		if (det.getElements("p")!='') {
			det.getElements("p")[0].addClass('firstPara');
			det.getElements("p").getLast().addClass('lastPara');
			//alert(det.getElements("p")[0].get('html'));
		}
	});
}


// sets up the flink
function setupFLink() {
	//alert($("hdr"));
	//alert($("hdr").getStyle("height"));
	//$("hdr").setStyle("height", "303px");
	//alert($("content").getPosition().y);
	//alert(1);
	$("fLink").position({
		position: 'topRight',
		edge: 'bottomRight',
		relativeTo:$("content")
	});
}


function setupVLink() {
	//$("vLink").setStyle("display","none");
	$("vLink").position({
		position: 'topLeft',
		edge: 'topRight',
		relativeTo:$("fLink"),
		offset: {x:-3, y:0}
	});
	//alert($("vLink").get('html'));
	$("vLink").addEvents({
		click: function(e){
			if(this.getElements("a").get('html')=="List View") {
				arrThumbs.each(function(biosTn) { biosTn.switchView("list"); });
				this.getElements("a").set("html","Thumb View");
				state = "list";
			} else {
				arrThumbs.each(function(biosTn) { biosTn.switchView("thumb"); });
				this.getElements("a").set("html","List View");
				state = "thumb";
			}			
			e.preventDefault();
		},
		mouseenter: function(e){
			this.addClass('over');
		},
		mouseleave: function(e){
			this.removeClass('over');
		}
	}, this);
}


// sets up the filter panel
function setupFilter() {
	//alert($("filtro"));
	try {
		var filter = $("filtro");
		filter.setStyle('display', 'none');
		filter.position({
			position: 'topRight',
			edge: 'topRight',
			relativeTo:$("content")
		});
		new HoverGroup({
			elements: [$("fLink"), $("filtro")],
			onEnter: function(){
				$("fLink").addClass('over');
				$("filtro").show();
			},
			onLeave: function(){
				$("fLink").removeClass('over');
				$("filtro").hide();
			}
		})
	}
	catch (e) { alert(e); }
}


function setupMediaShop() {
	var el = $("mediaShop").getElements("h2");
	el.addEvents({
		mouseover: function() { this.addClass("hover"); },
		mouseout: function() { this.removeClass("hover"); },
		click: function() { document.location.href = "/shop/"; }
	}, this);
}


function setupTicketShop() {
	var el = $("ticketShop").getElements("h2");
	el.addEvents({
		mouseover: function() { this.addClass("hover"); },
		mouseout: function() { this.removeClass("hover"); },
		click: function() { document.location.href = "/tickets/"; }
	}, this);
}


function setupInfoDesk() {
	
}

// INIT
window.addEvent('domready', function() { 
	if ($("GHCalendar")) { loadCalendar(); }
	if ($("logo")) { pinMenu(); }
	if ($$(".editor").length>0) { setupForms(); } 
	//alert($$(".editor").length=0);

	if ($$(".eventDetail").length>0) { alignCalendar(); }
	if ($("fLink")) { setupFLink(); }
	if ($("vLink")) { setupVLink(); }
	if ($$("dl").length>0) { setDlEvents(); }
	if ($("filtro")) { setupFilter(); }
	if ($$(".galleries").length>0) { gallerySlides(); }
	if ($$(".biosList").length>0) { setupBiosList(); }
	if ($$(".copy").length>0) { setupCopy(); }
	if ($$(".galleryImages").length>0 && $$(".galleries").length == 0) { fadeThumbs(); }
	if ($("ticker")) { setupTicker(); }
	if ($("featured")) { slideShow(); }
	if ($("infoDesk")) { setupInfoDesk(); }
	if ($$(".translate").length>0) { initTranslator(); }
	if ($("mediaShop")) { setupMediaShop(); }
	if ($("ticketShop")) { setupTicketShop(); }
	$$("a.noSpam").each(function(email) { var safeEmail = new SpamSafeEmail(email); })
	if ($$(".overText").length>0) { setupOverText(); }
	$("container").setStyle("visibility", "visible");
});