
var S1Cfg = {SITE_URL:"/",PTH_JS:"/js/lib/"};

var S1Local = {

	required: [],
	features: null,
	init_libs: null,
	v_forms: null,
	skip_trk: false,
	classes: {},

	init: function ()
	{
		if (this.features)
		{
			for(var i=0; i<this.features.length; i++)
			{
				switch (this.features[i])
				{
					case 'tr':
						// Table rulers
						this.tableruler();
					break;
					case 'mc':
						// TinyMCE
					break;
					case 'vl':
						// Set up video display links
						var links = document.getElementsByClassName('video_link');
						if (links)
						{
							for(var k=0; k<links.length; k++)
							{
								if (links[k].id) Event.observe(links[k],'click',this.videoDspWin.bind(this,links[k].id));
							}
						}
					break;
					case 'avp':
						// Add video and photo form display
						if ($('add_photo') && $('add_video'))
						{
							Event.observe('add_photo','click',this.dspPFile);
							Event.observe('add_video','click',this.dspVFile);
						}
					break;
					case 'ac':
						// Common add comment functionality
						if ($('add_comment'))
						{
							Event.observe('add_comment','click',this.dspComment);
						}
					break;
				}
			}
		}
		if (this.init_libs)
		{
			for(var i=0; i<this.init_libs.length; i++)
			{
				this[this.init_libs[i]].init();
			}
		}
		this.writeTRCK();
	},

	setFunc: function (data)
	{
		if (!data) return;
		var list = $w(data);
		if (!this.features)
		{
			this.features = list;
		}
		else
		{
			// append
		}
	},

	setLoaded: function (data)
	{
		if (!data) return;
		var list = $w(data);
		if (!this.init_libs)
		{
			this.init_libs = list;
		}
		else
		{
			for(var i=0; i<list.length; i++)
			{
				this.init_libs.push(list[i]);
			}
		}
	},

	loadRequired: function()
	{
		this.required.each(
			function(include) { S1Local.require(S1Cfg.PTH_JS+include+'.js') }
		);
	},

	loadAppend: function (js_file, lib, init, force, data)
	{
		if ( !this[lib] || force )
		{
			new Ajax.Request(S1Cfg.SITE_URL+js_file, {
				method: 'get',
				onSuccess: this.loadedJS.bindAsEventListener(this, lib, init, data)
				});
		}
		else if ( init && this[lib].init )
		{
			this[lib].init(data);
		}
	},

	loadedJS: function (r, lib, init, data)
	{
   		var resp = r.responseText;
   		if (resp) eval(resp);
   		if (init)
   		{
			eval("S1Local."+lib).init(data);
   		}
	},

	require: function(lib)
	{
	},

	// ---- COMMON

	setVForms: function (form, data)
	{
		if (!this.v_forms) this.v_forms = {};
		this.v_forms[form] = data;
	},

	tableruler: function ()
	{
	 if (document.getElementById && document.createTextNode)
	  {
	   var tables=document.getElementsByTagName('table');
	   for (var i=0;i<tables.length;i++)
	   {
	    if(tables[i].className=='ruler')
	    {
	     var trs=tables[i].getElementsByTagName('tr');
	     for(var j=0;j<trs.length;j++)
	     {
	      if(trs[j].parentNode.nodeName=='TBODY' && trs[j].parentNode.nodeName!='TFOOT')
	       {
	       trs[j].onmouseover=function(){this.className += ' ruled'; return false}
	       trs[j].onmouseout=function(){if(this.className.indexOf('evenRow') != -1) { this.className='evenRow'; } else { this.className = ''; } return false}
	     }
	    }
	   }
	  }
	 }
	},

	formValidate: function (form_elem)
	{
		if (!this.v_forms || !this.v_forms[form_elem.id]) return true;
		var errors = [];
		var checks = this.v_forms[form_elem.id];
		for(var i=0; i<checks.length; i++)
		{
			var field = checks[i].field;
			if (!$(field)) continue;
			var condition = false;
			if (checks[i].c)
			{
				// Check a condition for this rule
				switch (checks[i].ct)
				{
					case 'rs':
						// radio button selected
						if (!$(checks[i].c)) break;
						if ($(checks[i].c).checked)
						{
							condition = true;
						}
					break;
					default:
						break;
					break;
				}
			}
			else
			{
				condition = true;
			}
			if (condition)
			{
				var fail = false;
				switch (checks[i].v)
				{
					case 's':
						// Check that the string field has a value
						if ( $(field).value == "" || !$(field).value ) fail = true;
					break;
					case 'vp':
						// Check for a valid postcode
						var pc = $(field).value;
						if (pc && !this.checkPostCode(pc)) fail = true;
					break;
					case 'sv':
						// Check that a value has been selected
						var val = $(field).value;
						if (val == "null" || val == "") fail = true;
					break;
					case 've':
						// Check valid email address
						var email = $(field).value;
						if (email && !this.checkEmail(email)) fail = true;
					break;
					case 'cs':
						// Checkbox must be checked
						if (!$(field).checked) fail = true;
					break;
					default:
						fail = true;
					break;
				}
				if (fail)
				{
					errors.push(checks[i].fm);
					break;
				}
			}
		}
		if (errors.length < 1) return true;
		for(var i=0; i<errors.length; i++)
		{
			alert(errors[i]);
		}
		return false;
	},

	videoDspWin: function (elem_id)
	{
		var parts = elem_id.split(/_/);
		var cid = parts[1];
		if (cid)
		{
			window.open(S1Cfg.SITE_URL+'content.cgi?video=1&cid='+cid,'video_dsp','width=320,height=305')
		}
	},

	dspPFile: function()
	{
		$('add_photo').style.display = "none";
		$('file_photo').style.display = "block";
	},

	dspVFile: function ()
	{
		$('add_video').style.display = "none";
		$('file_video').style.display = "block";
	},

	dspComment: function ()
	{
		$('comment').style.display = "block";
	},

	checkPostCode: function (toCheck)
	{
		var alpha1 = "[abcdefghijklmnoprstuwyz]";                       // Character 1
		var alpha2 = "[abcdefghklmnopqrstuvwxy]";                       // Character 2
		var alpha3 = "[abcdefghjkstuw]";                                // Character 3
		var alpha4 = "[abehmnprvwxy]";                                  // Character 4
		var alpha5 = "[abdefghjlnpqrstuwxyz]";                          // Character 5

		var pcexp = new Array ();
		pcexp.push (new RegExp ("^(" + alpha1 + "{1}" + alpha2 + "?[0-9]{1,2})(\\s*)([0-9]{1}" + alpha5 + "{2})$","i"));
		pcexp.push (new RegExp ("^(" + alpha1 + "{1}[0-9]{1}" + alpha3 + "{1})(\\s*)([0-9]{1}" + alpha5 + "{2})$","i"));
		pcexp.push (new RegExp ("^(" + alpha1 + "{1}" + alpha2 + "?[0-9]{1}" + alpha4 +"{1})(\\s*)([0-9]{1}" + alpha5 + "{2})$","i"));
		pcexp.push (/^(GIR)(\s*)(0AA)$/i);
		pcexp.push (/^(bfpo)(\s*)([0-9]{1,4})$/i);
		pcexp.push (/^(bfpo)(\s*)(c\/o\s*[0-9]{1,3})$/i);
		pcexp.push (/^([A-Z]{4})(\s*)(1ZZ)$/i);
		var postCode = toCheck;
		var valid = false;
		for ( var i=0; i<pcexp.length; i++)
		{
			if (pcexp[i].test(postCode))
			{
				// The post code is valid - split the post code into component parts
				pcexp[i].exec(postCode);
				postCode = RegExp.$1.toUpperCase() + " " + RegExp.$3.toUpperCase();
				postCode = postCode.replace (/C\/O\s*/,"c/o ");
				valid = true;
				break;
			}
		}
		if (valid)
		{
			return postCode;
		}
		else
		{
			return false;
		}
	},

	checkEmail: function (str)
	{
		var at="@"
		var dot="."
		var lat=str.indexOf(at)
		var lstr=str.length
		var ldot=str.indexOf(dot)
		var valid = true;

		if (str.indexOf(at)==-1) valid = false;
		if (str.indexOf(at)==-1 || str.indexOf(at)==0 || str.indexOf(at)==lstr) valid = false;
		if (str.indexOf(dot)==-1 || str.indexOf(dot)==0 || str.indexOf(dot)==lstr) valid = false;
		if (str.indexOf(at,(lat+1))!=-1) valid = false;
		if (str.substring(lat-1,lat)==dot || str.substring(lat+1,lat+2)==dot) valid = false;
		if (str.indexOf(dot,(lat+2))==-1) valid = false;
		if (str.indexOf(" ")!=-1) valid = false;
		if (valid)
		{
			return str;
		}
		else
		{
			return false;
		}
	},

	showReg: function()
	{
		document.getElementById('hide1').style.display = 'block';
		document.getElementById('hide2').style.display = 'block';
	},

	hideReg: function()
	{
		document.getElementById('hide1').style.display = 'none';
		document.getElementById('hide2').style.display = 'none';
	},

	emailLink: function(user,domain)
	{
		document.write('<a href="mailto:' + user + '@' + domain + '">' + user + '@' + domain + '</a>');
	},

	checkCookie: function ()
	{
	    if (this.getTCookie()) return true;
	    this.setTCookie(30);
		if (this.getTCookie())
		{
			return true;
		}
	    else
		{
			return false;
		}
	},

	setTCookie: function (expiredays)
	{
	    var exdate=new Date();
	    exdate.setDate(exdate.getDate()+expiredays)
	        document.cookie="s1crm_t=1" +
	        ((expiredays==null) ? "" : "; expires="+exdate.toGMTString());
	},

	getTCookie:function ()
	{
	    if (document.cookie.match(/s1crm_t=/))
		{
			return true;
		}
	    else
		{
			return false;
		}
	},

	trkParams:function ()
	{
	   var domain = document.location.host;
	   var url = document.location.pathname;
	   var query_string = encodeURIComponent(document.location.search);
	   var mys1id = null;
	   var mycookie = document.cookie;
	   var pos = mycookie.indexOf("mys1_eid=");
	   if(pos != -1)
	   {
	      var start = pos + 9;
	      var end = mycookie.indexOf(";", start);
	      if(end == -1) end = mycookie.length;
	      mys1id = unescape(mycookie.substring(start,end));
	   }
	   var params = "dom=" + domain + "&qs=" + query_string + "&url=" + url;
	   if(mys1id)
	   {
	      params += "&mys1_eid=" + mys1id;
	   }
	   else
	   {
		  var rv = Math.round(1000000*Math.random());
	      params += "&rv=" + rv;
	   }
	   return params;
	},

	writeTRCK:function ()
	{
	    if (this.skip_trk) return false;
	    var ccheck = this.checkCookie();
	    if (!ccheck) return;
		    var params = this.trkParams();
		    var i=new Image(1,1);
		    i.src = "http://crm.s1now.com/tracker.gif?"+params;
		    i.onload = function() { return ;}
	}

};

S1Local.loadRequired();
window.onload = function ()
{
	S1Local.init();
}


// homepage pysh form functions

function pyshExpand(t) {
	t.style.height = "200px";
}

function pyshBlur(t) {
	if (!t.value) {
		t.style.height = "70px";
	}
}

function pyshAlertScotlistings() {
	alert('You will now be taken to our sister site, Scotlistings,\nto enter details of your event.');
}

// end homepage pysh functions

/**
 * Some common functions
 */
S1Local.core = {

	/**
	 * Get the window dimensions
	 */
	getWindowDims: function ()
	{
		var width, height;
		var w = window;
		var width = w.innerWidth || (w.document.documentElement.clientWidth || w.document.body.clientWidth);
		var height = w.innerHeight || (w.document.documentElement.clientHeight || w.document.body.clientHeight);
		return {width:width, height:height};
	},

	/**
	 *
	 */
	isFunction: function (a)
	{
		return typeof a == 'function';
	},

	/**
	 *
	 */
	isArray: function (a)
	{
		if (a == undefined) return false;
 		return this.isObject(a) && a.constructor == Array;
	},

	/**
	 *
	 */
	isObject: function (a)
	{
		return (typeof a == 'object' && !!a) || this.isFunction(a);
	}

};

S1Local.winloc = {

	addParam: function (param, value)
	{
		if (typeof window.location.parameters == "undefined") this.setupParams();
		window.location.parameters[param] = value;
	},

	clearParams: function (params)
	{
		if (typeof window.location.parameters == "undefined") this.setupParams();
		if (params)
		{
			for(var i=0; index<params.length; i++)
			{
				window.location.parameters[params[i]] = 0;
			}
		}
		else
		{
			for(var i in window.location.parameters)
			{
				window.location.parameters[i] = 0;
			}
		}
	},

	setupParams: function setupParameters()
	{
		var parameters = new Object();
		if(window.location.search)
		{
			var paramArray = window.location.search.substr(1).split('&');
			var length = paramArray.length;
			for (var index = 0;index <length; index++ )
			{
				var param = paramArray[index].split('=');
				var name = param[0];
				var value = (typeof param[1] == "string") ? decodeURIComponent(param[1].replace(/\+/g, ' ')) : null;
				parameters[name] = value;
			}
		}
		window.location.parameters = parameters;
	},

	getParam: function (name)
	{
		if (typeof window.location.parameters == "undefined") this.setupParams();
		return window.location.parameters[name];
	},

	getLoc: function ()
	{
		var loc = window.location.toString();
		var pref = loc.split("?");
		var qstr = "";
		for (p in window.location.parameters)
		{
			qstr+="&"+p+"="+window.location.parameters[p];
		}
		qstr = qstr.replace(/^&/,"?");
		return pref[0]+qstr;
	}

};
