/**
 * Pilkington Glass - Javascript
 *
 * @author: Andy Thomas
 * @date: 04/08/2008
 */

/**
 * window.onload
 */
 
window.onload = function() {
	checkFormFields('contact-form');
	checkFormFields('admin-form');
	
	var date_field = document.getElementById('article-dated');
	
	if (date_field) {
		addDatePicker();
		
		prepcalendar('',ccm,ccy);
		
		date_field.parentNode.className = 'date-picker';
		
		addEventListener(date_field,'focus',function(e) {
			e = (e) ? e : window.event;
			var date_field = document.getElementById('article-dated');
			this.select();
			lcs(this);
			if (e.stopPropagation)
				e.stopPropagation();
			else
				e.returnValue = false;
		},false);
		
		addEventListener(date_field,'click',function(e) {
			e = (e) ? e : window.event;
			this.select();
			lcs(document.getElementById('article-dated'));
			if (e.stopPropagation)
				e.stopPropagation();
			else
				e.returnValue = false;
		},false);
		
		addEventListener(date_field.parentNode,'focus',function(e) {
			e = (e) ? e : window.event;
			var date_field = document.getElementById('article-dated');
			date_field.select();
			lcs(date_field);
			if (e.stopPropagation)
				e.stopPropagation();
			else
				e.returnValue = false;
		},false);
		
		addEventListener(date_field.parentNode,'click',function(e) {
			e = (e) ? e : window.event;
			var date_field = document.getElementById('article-dated');
			date_field.select();
			lcs(date_field);
			if (e.stopPropagation)
				e.stopPropagation();
			else
				e.returnValue = false;
		},false);
	}
	
	var fas_postcode = document.getElementById('fas-uk-term');
	
	if (fas_postcode) {
		addEventListener(fas_postcode,'focus',function(e) {
				e = (e) ? e : window.event;
				if (this.value=='Enter Postcode')
					this.value='';
			},false);
		
		addEventListener(fas_postcode,'blur',function(e) {
				e = (e) ? e : window.event;
				if (this.value=='')
					this.value='Enter Postcode';
			},false);
	}
	
	
	if (navigator.appName=='Microsoft Internet Explorer') {
		var fix_ie_lit = getElementsByClass('col-lit-title',document.getElementById('content'));
		
		if (fix_ie_lit.length > 0) {
			for(i=0;i<fix_ie_lit.length;i++) {
				fix_ie_lit[i].style.height = 'auto';
				fix_ie_lit[i].style.padding = ((97 - fix_ie_lit[i].offsetHeight) / 2) + 'px 16px';
			}
		}
	}
}

/**
 * add_sb
 * to add social bookmarking icons
 */
function add_sb(title,url) {
	document.write(
		'<ul class="social_bookmarks">' +
    	add_sb_icon('digg',			'digg',			'http://digg.com/submit?phase=2&amp;url=' + url + '&amp;title=' + title) +
		add_sb_icon('technorati',	'Technorati',	'http://www.technorati.com/faves/?add=' + url) +
		add_sb_icon('delicious', 	'del.icio.us', 	'http://del.icio.us/post?url=' + url + '&amp;title=' + title) +
		add_sb_icon('propeller', 	'Propeller', 	'http://www.propeller.com/submit/?U=' + url + '&T=' + title) + 
		add_sb_icon('stumbleupon', 	'StumbleUpon', 	'http://www.stumbleupon.com/submit?url=' + url + '&title=' + title) +
		add_sb_icon('reddit', 		'reddit', 		'http://reddit.com/submit?url=' + url + '&amp;title=' + title) +
		'</ul>'
	);
	externalLinks();
}

function add_sb_icon(icon, name, url) {
	return '<li class="sb_' + icon + '"><a href="' + url + '" title="Add to ' + name +'" rel="external">' + name + '</a></li> ';
}

/**
 * checkFormFields
 * quick client-side validation to check that no fields on a form are left empty.
 */

function checkFormFields(byClass) {
	var forms = getElementsByClass(byClass,document.getElementById('content'));
	
	if (forms.length > 0) {
		for(i=0;i<forms.length;i++) {
			addEventListener(forms[i],'submit',function(e) {
				e = (e) ? e : window.event;
				
				var fields = this.getElementsByTagName('*');
				var empty = 0;
				
				for (f=0;f<fields.length;f++) {
					if ( fields[f].value == '')
						empty++;
				}
				
				if (empty>0) {
					alert('Please fill out all fields on the form.');
					if (e.preventDefault)
						e.preventDefault();
					if (e.stopPropagation)
						e.stopPropagation();
					else
						e.returnValue = false;
				}
			},false);
		}
	}
}

/**
 * getElementByClass
 * grab elements by their class name
 */
function getElementsByClass(needle,area) 
{
	area = area || document;
	var my_array = area.getElementsByTagName("*");
	var retvalue = new Array();
	var j = 0;

	for (var i=0;i<my_array.length;i++) {
		var c = ' ' + my_array[i].className + ' ';
		if (c.indexOf(' ' + needle + ' ') != -1) retvalue[j++] = my_array[i];
	}
	
	return retvalue;
}

/**
 * addEventListener
 * cross browser event listener.
 */
function addEventListener(el,et,h,c) {
	if (el.addEventListener)
		el.addEventListener(et,h,c);
	else if (el.attachEvent)
		eval('el.on' + et + ' = ' + h);
}

/**
 * addFlashOverlay
 * Add an overlay to the page for use with Flash.
 */
function addFlashOverlay(id,title,swftype,width,height,bgcol) {
	var o		= document.createElement('div');
	o.id		= 'overlay';
	o.className = 'overlay_' + id;
	
	// overlay background
	var ob 		= document.createElement('div');
	ob.id		= 'overlay-bg';
	o.appendChild(ob);
	
	// overlay content
	var oc				= document.createElement('div');
	oc.id				= 'overlay-content';
	oc.style.width		= width + 'px';
	oc.style.height		= (parseInt(height) + 25) + 'px';
	oc.style.marginLeft	= (width/2 * -1) + 'px';
	oc.style.marginTop	= (height/2 * -1) + 'px';
	
	/* */
	var ocf			= document.createElement('div');
	ocf.id			= id;
	ocf.innerHTML	= '<p>To view the <em>' + title + '</em> ' + swftype + ', you will need to <a href="http://www.adobe.com/shockwave/download/download.cgi?P1_Prod_Version=shockwaveFlash" title="Install the Adobe Flash Player">install the Adobe Flash plugin.</a></p>';
	oc.appendChild(ocf);
	
	// 'remove overlay' anchor
	var oa 		= document.createElement('a');
	oa.appendChild(document.createTextNode('Close'))
	oa.id		= 'overlay-close';
	oa.href 	= '#';
	oa.onclick 	= function(){removeOverlay();return false;}
	oc.appendChild(oa);
	
	o.appendChild(oc);
	document.body.appendChild(o);
	
	// attempt to replace our text with the SWFObject flash embedding technique.
	if (SWFObject) {
		var so = new SWFObject("/swf/compare_glass.swf", "flash_" + id, width, height, "8", bgcol);
		so.write(id);
	}
	
	document.body.style.cursor	= 'wait';
	fadeById('overlay-bg', 0, .75, 500);
	fadeById('overlay-content', 0, 1, 500);
	setTimeout('document.body.style.cursor = "default"', 500);
	// blur();
}

/**
 * removeOverlay
 * Removes the overlay.
 */
function removeOverlay() {
	var o = document.getElementById('overlay');
	if (o) {
		document.body.style.cursor	= 'wait';
		fadeById('overlay-bg', .75, 0, 500);
		fadeById('overlay-content', 1, 0, 500);
		setTimeout('document.body.style.cursor = "default"', 500);
		setTimeout('document.body.removeChild(document.getElementById("overlay"))', 500);
	}
}

function fadeById(id,from,to,duration) {
	var f = (duration > 999) ? 30 * (duration / 1000) : 30;
	var s = ((to - from) / f);
	var t = duration / f;
	
	for (i = 1; i <= f; i++) {
		setTimeout('setOpacity(document.getElementById(\'' + id + '\'),' + (from + (i*s)) + ')', i*t);
	}
}

/**
 * setOpacity
 * set the opacity for a given element;
 */
function setOpacity(el,o) {
	el.style.opacity = o;
	el.style.MozOpacity = o;
	el.style.KhtmlOpacity = o;
	el.style.filter = "alpha(opacity=" + (o * 100) + ");";
}

/**
 * externalLinks
 * open any anchor with the rel="external"
 */
function externalLinks() {
    if (!document.getElementsByTagName) return;

    var anchors = document.getElementsByTagName("a");

    for ( var i=0; i < anchors.length; i++ ) {
        var anchor = anchors[i];

        if ( anchor.getAttribute("href") && anchor.getAttribute("rel") == "external" ) {
            if ( anchor.getAttribute("className") ) {
                anchor.target = anchor.getAttribute("className");
            }
            else {
                anchor.target = "_blank";
            }
        }
    }
}


/* start of calendar */
/* --- Swazz Javascript Calendar ---
/* --- v 1.0 3rd November 2006
By Oliver Bryant
http://calendar.swazz.org

Edits for Pilkington Self Cleaning Glass website by Andy Thomas (04/08/2008) */

function getObj(objID)
{
    if (document.getElementById) {return document.getElementById(objID);}
    else if (document.all) {return document.all[objID];}
    else if (document.layers) {return document.layers[objID];}
}

function checkClick(e) {
	e?evt=e:evt=event;
	CSE=evt.target?evt.target:evt.srcElement;
	if (getObj('fc'))
		if (!isChild(CSE,getObj('fc')))
			getObj('fc').style.display='none';
}

function isChild(s,d) {
	while(s) {
		if (s==d) 
			return true;
		s=s.parentNode;
	}
	return false;
}

function Left(obj)
{
	var curleft = 1;
	if (obj.offsetParent)
	{
		while (obj.offsetParent)
		{
			curleft += obj.offsetLeft
			obj = obj.offsetParent;
		}
	}
	else if (obj.x)
		curleft += obj.x;
	return curleft;
}

function Top(obj)
{
	var curtop = 0;
	if (obj.offsetParent)
	{
		while (obj.offsetParent)
		{
			curtop += obj.offsetTop
			obj = obj.offsetParent;
		}
	}
	else if (obj.y)
		curtop += obj.y;
	return curtop;
}

function addDatePicker() {
	var datepicker 			= document.createElement('div');
	datepicker.id		= 'date-picker';
	var dpMarkup = 	'<table id="fc" style="position:absolute;border-collapse:collapse;background:#FFFFFF;border:1px solid #ABABAB;display:none" cellpadding=2>' +
					'<tr><td style="cursor:pointer" onclick="csubm()">&lt;&lt;</td><td colspan=5 id="mns" align="center" style="font:bold 13px Arial"></td><td align="right" style="cursor:pointer" onclick="caddm()">&gt;&gt;</td></tr>' +
					'<tr><td align=center style="background:#ABABAB;font:12px Arial">S</td><td align=center style="background:#ABABAB;font:12px Arial">M</td><td align=center style="background:#ABABAB;font:12px Arial">T</td><td align=center style="background:#ABABAB;font:12px Arial">W</td><td align=center style="background:#ABABAB;font:12px Arial">T</td><td align=center style="background:#ABABAB;font:12px Arial">F</td><td align=center style="background:#ABABAB;font:12px Arial">S</td></tr>';
	
	for(var kk=1;kk<=6;kk++) {
		dpMarkup += '<tr>';
		for(var tt=1;tt<=7;tt++) {
			num=7 * (kk-1) - (-tt);
			dpMarkup += '<td id="v' + num + '" style="width:18px;height:18px">&nbsp;</td>';
		}
		dpMarkup += '</tr>';
	}
	dpMarkup += '</table>';
	
	datepicker.innerHTML = dpMarkup; 
	
	document.body.appendChild(datepicker);
	
	document.all?document.attachEvent('onclick',checkClick):document.addEventListener('click',checkClick,false);
}


// Calendar script
var now = new Date;
var sccm=now.getMonth();
var sccy=now.getFullYear();
var ccm=now.getMonth();
var ccy=now.getFullYear();

var updobj;
function lcs(ielem) {
	updobj=ielem;
	getObj('fc').style.left=Left(ielem) + 'px';
	getObj('fc').style.top=Top(ielem)+ielem.offsetHeight + 'px';
	getObj('fc').style.display='';
	
	// First check date is valid
	curdt=ielem.value;
	curdtarr=curdt.split('/');
	isdt=true;
	for(var k=0;k<curdtarr.length;k++) {
		if (isNaN(parseInt(curdtarr[k])))
			isdt=false;
	}
	if (isdt&(curdtarr.length==3)) {
		ccm=curdtarr[1]-1;
		ccy=curdtarr[2];
		prepcalendar(curdtarr[0],curdtarr[1]-1,curdtarr[2]);
	}
	
}

function evtTgt(e)
{
	var el;
	if(e.target)el=e.target;
	else if(e.srcElement)el=e.srcElement;
	if(el.nodeType==3)el=el.parentNode; // defeat Safari bug
	return el;
}
function EvtObj(e){if(!e)e=window.event;return e;}
function cs_over(e) {
	evtTgt(EvtObj(e)).style.background='#FFCC66';
}
function cs_out(e) {
	evtTgt(EvtObj(e)).style.background='#C4D3EA';
}
function cs_click(e) {
	var temp_value=calvalarr[evtTgt(EvtObj(e)).id.substring(1,evtTgt(EvtObj(e)).id.length)];
	temp_value = temp_value.split('/');
	
	temp_value[0] = (temp_value[0]<10) ? '0' + temp_value[0] : temp_value[0];
	temp_value[1] = (temp_value[1]<10) ? '0' + temp_value[1] : temp_value[1];
	
	updobj.value=temp_value[0] + '/' + temp_value[1] + '/' + temp_value[2];
	getObj('fc').style.display='none';
	
}

var mn=new Array('JAN','FEB','MAR','APR','MAY','JUN','JUL','AUG','SEP','OCT','NOV','DEC');
var mnn=new Array('31','28','31','30','31','30','31','31','30','31','30','31');
var mnl=new Array('31','29','31','30','31','30','31','31','30','31','30','31');
var calvalarr=new Array(42);

function f_cps(obj) {
	obj.style.background='#C4D3EA';
	obj.style.font='10px Arial';
	obj.style.color='#333333';
	obj.style.textAlign='center';
	obj.style.textDecoration='none';
	obj.style.border='1px solid #6487AE';
	obj.style.cursor='pointer';
}

function f_cpps(obj) {
	obj.style.background='#C4D3EA';
	obj.style.font='10px Arial';
	obj.style.color='#ABABAB';
	obj.style.textAlign='center';
	obj.style.textDecoration='line-through';
	obj.style.border='1px solid #6487AE';
	obj.style.cursor='default';
}

function f_hds(obj) {
	obj.style.background='#FFF799';
	obj.style.font='bold 10px Arial';
	obj.style.color='#333333';
	obj.style.textAlign='center';
	obj.style.border='1px solid #6487AE';
	obj.style.cursor='pointer';
}

// day selected
function prepcalendar(hd,cm,cy) {
	now=new Date();
	sd=now.getDate();
	td=new Date();
	td.setDate(1);
	td.setFullYear(cy);
	td.setMonth(cm);
	cd=td.getDay();
	getObj('mns').innerHTML=mn[cm]+ ' ' + cy;
	marr=((cy%4)==0)?mnl:mnn;
	for(var d=1;d<=42;d++) {
		f_cps(getObj('v'+parseInt(d)));
		if ((d >= (cd -(-1))) && (d<=cd-(-marr[cm]))) {
			dip=((d-cd < sd)&&(cm==sccm)&&(cy==sccy));
			htd=((hd!='')&&(d-cd==hd));
			if (dip)
				f_cpps(getObj('v'+parseInt(d)));
			else if (htd)
				f_hds(getObj('v'+parseInt(d)));
			else
				f_cps(getObj('v'+parseInt(d)));

			getObj('v'+parseInt(d)).onmouseover=(dip)?null:cs_over;
			getObj('v'+parseInt(d)).onmouseout=(dip)?null:cs_out;
			getObj('v'+parseInt(d)).onclick=(dip)?null:cs_click;
			
			getObj('v'+parseInt(d)).innerHTML=d-cd;	
			calvalarr[d]=''+(d-cd)+'/'+(cm-(-1))+'/'+cy;
		}
		else {
			getObj('v'+d).innerHTML='&nbsp;';
			getObj('v'+parseInt(d)).onmouseover=null;
			getObj('v'+parseInt(d)).onmouseout=null;
			getObj('v'+parseInt(d)).style.cursor='default';
			}
	}
}

function caddm() {
	marr=((ccy%4)==0)?mnl:mnn;
	
	ccm+=1;
	if (ccm>=12) {
		ccm=0;
		ccy++;
	}
	//cdayf();
	prepcalendar('',ccm,ccy);
}

function csubm() {
	marr=((ccy%4)==0)?mnl:mnn;
	
	ccm-=1;
	if (ccm<0) {
		ccm=11;
		ccy--;
	}
	//cdayf();
	prepcalendar('',ccm,ccy);
}

function cdayf() {
if ((ccy>sccy)|((ccy==sccy)&&(ccm>=sccm)))
	return;
else {
	ccy=sccy;
	ccm=sccm;
	cfd=scfd;
	}
}

/* end of calendar */