    window.onload = function() {
      (document.all && !window.print) ? null : setForm();
      theatreSetup();
      cal_init();
	  //advSearchUpdateSelect("b=all&func=styles");
	  //advSearchUpdateSelect("b=all&s=all&func=colour");
    }
    
var caldatecount=0; 
 
////////////////////////////////////////////////////////////////////////////////////////////
// select replacemant stuff for advanced search drop down
function theatreSetup(){
	if(document.getElementById('venueupdater')){
		if(document.getElementById('columna')){
			//write keyword form
			var myConn = new XHConn();
			myConn.connect("/javascript/search-keywords.csv", "GET", "", theatreMakeTicks);				
		}	
	}
} 

function theatreMakeTicks(data){
	var keywords=document.getElementById('duocms_keywords').value;
	var mmn_trup=document.getElementById('venueupdater');
	var csv="\n"+data.responseText.replace(/^\s+|\s+$/, '');//add line feed to begining to all line start with newline.
	var rows=csv.split("\r");
	var html='';
	var prevsection='';
	
	for (i=0;i<rows.length;i++){
		var cols=rows[i].split(",");
		var section=cols[0];
		var label=cols[1];
		var keyword=cols[2];
		if(section!=prevsection){
			html+="<h2>"+section+"</h2>";
			prevsection=section;
		}
		var keycount=keywords.split(keyword);
		if(keycount.length>1){
			html+="<input type='checkbox' id='"+keyword+"' onclick='theatreKeywords(\""+keyword+"\",this);' checked /><label>"+label+"</label><br />";
		}else{
			html+="<input type='checkbox' id='"+keyword+"' onclick='theatreKeywords(\""+keyword+"\",this);' /><label>"+label+"</label><br />";
		}		
	}
	mmn_trup.innerHTML=html; 
}

function theatreKeywords(keyword,object){
	//1st remove keyword from keywords list
	var keywords=document.getElementById('duocms_keywords');
	var re = new RegExp(" "+keyword+" ", 'gi');
	keywords.value=keywords.value.replace(re,'');	
	if(object.checked){
		keywords.value=keywords.value+' '+keyword+' ';
	}
}

function theatreMakeSearch(){
	var fields=new Array('planner_when','planner_kids','planner_eat','planner_dance');
	var field='';
	var searchString='';
	for(var i=0;i<fields.length;i++){
		field=document.getElementById(fields[i]);	
		if(field.value){
			searchString+=field.value+" ";	
		}
	}	
	searchString=searchString.replace('/ /g','+');
	window.location.href='/search/?q='+searchString;
}


//------------------------------------------------------------------------------------------
//advanced controls for adding competition questions

function competitionTools(){
	if(document.getElementById('competitionControls') && document.getElementById('columnd')){
		var toolbar=document.getElementById('competitionControls');
		toolbar.innerHTML='<div class="competionAddButton"><a onclick="javascript:void(competitionAddQuestion())">add question</a></div>';		
		document.getElementById('columnd').style.border="1px solid red;";
	}
}

function competitionAddQuestion(){
	var formArea=document.getElementById('columnd');
	//count inputs
	var inputs=formArea.getElementsByTagName('INPUT');
	var total=inputs.length+1;	
	formArea.innerHTML+='<div>'+total+'. your question here</div><input class="fullWidth" name="answer'+total+'" />';
}
//apply for competition
function competitionValidateAndSend(){
	
	//check user info form - the question answers are optional
	var form=document.getElementById('competform'); 	
	var field='';
	var errorcount=0;
	var question='';
	var formFields=form.getElementsByTagName('INPUT');
	for(var i=0;i<formFields.length;i++){
		field=formFields[i];
		if(field.value.length<1 && field.name!="telephone" && field.name!="country"){
			field.style.border="1px solid red";
			errorcount++;
		}else{
			field.style.border="1px solid #cccccc";
		}
	}	
	if(errorcount>0){
		alert('You must complete the form fields marked in red. \nPlease complete these and try again.');	
	}else{
		//submit all form data
		formFields=form.elements;
		var savingData='';
		for(var i=0;i<formFields.length;i++){
			field=formFields[i];
			if(field.name){
				savingData+=field.name+"="+field.value+"&";
			}
		}
		//add q & a's
		formFields=document.getElementsByTagName('input');		
		for(var i=0;i<formFields.length;i++){
			field=formFields[i];
			if(field.name.substr(0,6)=="answer"){
				question=field.parentNode.previousSibling.previousSibling.innerHTML.replace('\n','');
				if(whichBrs()=="ie"){
					question=field.parentNode.previousSibling.innerHTML.replace(/[\n\r\t]*/,'');
				}else{
					question=field.parentNode.previousSibling.previousSibling.innerHTML.replace(/[\n\r\t]*/,'');	
				}
				savingData+=question+"="+field.value+"&";
			}
		}
		var myConn = new XHConn();
		myConn.connect("/competition.php", "POST", savingData, competitionRedirect);	
	}
}

function competitionRedirect(data){
	window.location.href=data.responseText;	
}

//------------------------------------------------------------------------------------------
//advanced controls for events calander
function cal_init(){
	if(document.getElementById('calEvents')){
		if(document.getElementById('columna')){	
			cal_getEvents();
		}
	}
}

function cal_getEvents(){
	var myConn = new XHConn();
	var page_id=document.getElementById('page_id').value;
	var savingData="func=getDates&page_id="+page_id;
	myConn.connect("/events.php", "POST", savingData, cal_getEvents_res);
}

function cal_getEvents_res(data){
	var data=eval('(' +data.responseText + ')');
	var list=document.getElementById('calEvents');
	var html='<table class="tabledefault"><thead><th>start date</th><th>end date</th><th>repeat</th></thead><tbody>';
	if(data.error){
		html+=data.error;	
	}else{		
		var listdata=data.info;
		var sel;
		for(var row in listdata){
			if(listdata[row].id){
				sel=new Array();
				sel[listdata[row].repeat]='selected';
				html+='<tr><td><form><input type="hidden" name="id" value="'+listdata[row].id+'" /><input class="cal_date" name="start" id="f_date_'+listdata[row].id+'" value="'+listdata[row].start+'" /><button type="reset" id="f_trigger_'+listdata[row].id+'" >...</button></td><td><input class="cal_date" name="end" id="f_date_E'+listdata[row].id+'" value="'+listdata[row].end+'"/><button type="reset" id="f_trigger_E'+listdata[row].id+'" >...</button></td><td>';
				html+='<select name="repeat">';
				html+='<option '+sel[0]+' value="0">no repeat</option>';
				html+='<option '+sel[1]+' value="1">daily</option>';
				html+='<option '+sel[2]+' value="2">weekly</option>';
				html+='<option '+sel[3]+' value="3">fortnightly</option>';
				html+='<option '+sel[4]+' value="4">monthly</option>';
				html+='<option '+sel[5]+' value="5">bi-monthly</option>';
				html+='</select><input type="button" onclick="cal_delrow(this)" value=" x " title="delete this date range" /></form></td></tr>';	
			}
		}
	}
	html+='</tbody></table><div id="cal_buttons"><input class="cal_button" type="button" onclick="cal_addDate();" value="add date range" /><input class="cal_button" type="button" type="button" onclick="cal_saveAllEvents()" value="save dates" /></div><div id="cal_saving">saving</div>';
	list.innerHTML=html;	
	for(var row in listdata){
		if(listdata[row].id){
			cal_addCals(listdata[row].id);
		}
	}	
}

function cal_addCals(id){
	    Calendar.setup({
		inputField     :    "f_date_"+id,     // id of the input field
		ifFormat       :    "%d/%m/%Y",     // format of the input field (even if hidden, this format will be honored)
		daFormat       :    "%A, %B %d, %Y",// format of the displayed date
		button         :    "f_trigger_"+id,  // trigger button (well, IMG in our case)
		align          :    "Tl",           // alignment (defaults to "Bl")
		singleClick    :    true
    	});
    	Calendar.setup({
			inputField     :    "f_date_E"+id,     // id of the input field
			ifFormat       :    "%d/%m/%Y",     // format of the input field (even if hidden, this format will be honored)
			daFormat       :    "%A, %B %d, %Y",// format of the displayed date
			button         :    "f_trigger_E"+id,  // trigger button (well, IMG in our case)
			align          :    "Tl",           // alignment (defaults to "Bl")
			singleClick    :    true
	    });
}

function cal_saveEvent(row){
	var myConn = new XHConn();
	var inputs=row.getElementsByTagName('input');
	var selects=row.getElementsByTagName('select');
	var page_id=document.getElementById('page_id').value;
	var id=inputs[0].value;
	var start=inputs[1].value;
	var end=inputs[2].value;
	var repeat=selects[0].value;
	var savingData="func=updateDate&page_id="+page_id+"&id="+id+"&start="+start+"&end="+end+"&repeat="+repeat;
	myConn.connect("/events.php", "POST", savingData, cal_saveEvent_res);
}

function cal_saveAllEvents(){
	var list=document.getElementById('calEvents');
	var tblBody = list.getElementsByTagName('tbody');
	var trs=tblBody[0].getElementsByTagName('TR');
	for(var i=0;i<trs.length;i++){
		caldatecount++;
		document.getElementById('cal_buttons').style.display='none';
		document.getElementById('cal_saving').style.display='block';
		cal_saveEvent(trs[i]); 
	}
}

function cal_saveEvent_res(data){
	caldatecount--;
	if(caldatecount==0){
		document.getElementById('cal_buttons').style.display='block';
		document.getElementById('cal_saving').style.display='none';	
	}
}

function cal_addDate(){
	var list=document.getElementById('calEvents');
	var tblBody = list.getElementsByTagName('tbody');
	//var newNode = tblBody[0].rows[0].cloneNode(true);
	var row=tblBody[0].insertRow(-1); 
	var rowcount="00"+tblBody[0].childNodes.length;
	var cell=row.insertCell(-1); 
	cell.innerHTML='<form><input type="hidden" name="id" value="" /><input class="cal_date" name="start" value="" id="f_date_'+rowcount+'"/><button type="reset" id="f_trigger_'+rowcount+'" >...</button>'; 
	cell=row.insertCell(-1); 
	cell.innerHTML='<input class="cal_date" name="end" value="" id="f_date_E'+rowcount+'"/><button type="reset" id="f_trigger_E'+rowcount+'" >...</button>';
	cell=row.insertCell(-1); 
	cell.innerHTML='<select name="repeat"><option value="0">no repeat</option><option value="1">daily</option><option value="2">weekly</option><option value="3">fortnightly</option><option value="4">monthly</option><option value="5">bi-monthly</option></select><input type="button" value=" x " title="delete" /></form>';
	cal_addCals(rowcount);
	//alert(rowcount);
}

function cal_delrow(item){
	if(!confirm('Are you sure you want to delete this daterange?\nThis can not be undone.')){return;}
	var row=item.parentNode.parentNode;
	var inputs=row.getElementsByTagName('input');
	var id=inputs[0].value;
	if(id){//remove from db
		caldatecount++;
		var myConn = new XHConn();	
		var savingData="func=deleteDate&id="+id;
		myConn.connect("/events.php", "POST", savingData, cal_delrow_res);
	}
	row.parentNode.removeChild(row);	
}

function cal_delrow_res(data){
	//alert(data.responseText);
}

function cal_selDate(seldate){
	if(seldate){//remove from db
		var myConn = new XHConn();	
		var savingData="date="+seldate+"&func=output";
		
		myConn.connect("/calendar.php", "POST", savingData, cal_showLoadedCal);
	}
}
function cal_showLoadedCal(data){
	var data=data.responseText;
	document.getElementById('eventCalDiv').innerHTML=data;
}


//============================================================================================
/** XHConn - Simple XMLHTTP Interface - bfults@gmail.com - 2005-04-08        **
 ** Code licensed under Creative Commons Attribution-ShareAlike License      **
 ** http://creativecommons.org/licenses/by-sa/2.0/                           **/
if(document.getElementById('statusbar')){
	var oldStatusBackground=document.getElementById('statusbar').style.backgroundImage;
}
function XHConn()
{
  var xmlhttp, bComplete = false;
  try { xmlhttp = new ActiveXObject("Msxml2.XMLHTTP"); }
  catch (e) { try { xmlhttp = new ActiveXObject("Microsoft.XMLHTTP"); }
  catch (e) { try { xmlhttp = new XMLHttpRequest(); }
  catch (e) { xmlhttp = false; }}}
  if (!xmlhttp) return null;
  this.connect = function(sURL, sMethod, sVars, fnDone)
  {
    if (!xmlhttp) return false;
    bComplete = false;
    sMethod = sMethod.toUpperCase();

    try {
    	//before load, set statusbar to loading icon
    	if(document.getElementById('statusbar')){
    		document.getElementById('statusbar').style.backgroundImage="url(/duocms-resources/icons/loading2.gif)";
    	}
    		
      if (sMethod == "GET")
      {
        xmlhttp.open(sMethod, sURL+"?"+sVars, true);
        sVars = "";
      }
      else
      {
        xmlhttp.open(sMethod, sURL, true);
        xmlhttp.setRequestHeader("Method", "POST "+sURL+" HTTP/1.1");
        xmlhttp.setRequestHeader("Content-Type",
          "application/x-www-form-urlencoded");
      }
      xmlhttp.onreadystatechange = function(){
        if (xmlhttp.readyState == 4 && !bComplete){
        	//after loaded set statusbar back to old background
        	if(document.getElementById('statusbar') && oldStatusBackground){
	    		document.getElementById('statusbar').style.backgroundImage=oldStatusBackground;
    		}else if(document.getElementById('statusbar')){
    			document.getElementById('statusbar').style.backgroundImage='';
    		}
        	
          bComplete = true;
          fnDone(xmlhttp);
        }};
      xmlhttp.send(sVars);
    }
    catch(z) { return false; }
    return true;
  };
  return this;
}

//JSON Parser = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = 

(function () {
    var m = {
            '\b': '\\b',
            '\t': '\\t',
            '\n': '\\n',
            '\f': '\\f',
            '\r': '\\r',
            '"' : '\\"',
            '\\': '\\\\'
        },
        s = {
            array: function (x) {
                var a = ['['], b, f, i, l = x.length, v;
                for (i = 0; i < l; i += 1) {
                    v = x[i];
                    f = s[typeof v];
                    if (f) {
                        v = f(v);
                        if (typeof v == 'string') {
                            if (b) {
                                a[a.length] = ',';
                            }
                            a[a.length] = v;
                            b = true;
                        }
                    }
                }
                a[a.length] = ']';
                return a.join('');
            },
            'boolean': function (x) {
                return String(x);
            },
            'null': function (x) {
                return "null";
            },
            number: function (x) {
                return isFinite(x) ? String(x) : 'null';
            },
            object: function (x) {
                if (x) {
                    if (x instanceof Array) {
                        return s.array(x);
                    }
                    var a = ['{'], b, f, i, v;
                    for (i in x) {
                        v = x[i];
                        f = s[typeof v];
                        if (f) {
                            v = f(v);
                            if (typeof v == 'string') {
                                if (b) {
                                    a[a.length] = ',';
                                }
                                a.push(s.string(i), ':', v);
                                b = true;
                            }
                        }
                    }
                    a[a.length] = '}';
                    return a.join('');
                }
                return 'null';
            },
            string: function (x) {
                if (/["\\\x00-\x1f]/.test(x)) {
                    x = x.replace(/([\x00-\x1f\\"])/g, function(a, b) {
                        var c = m[b];
                        if (c) {
                            return c;
                        }
                        c = b.charCodeAt();
                        return '\\u00' +
                            Math.floor(c / 16).toString(16) +
                            (c % 16).toString(16);
                    });
                }
                return '"' + x + '"';
            }
        };

    Object.prototype.toJSONString = function () {
        return s.object(this);
    };

    Array.prototype.toJSONString = function () {
        return s.array(this);
    };
})();

String.prototype.parseJSON = function () {
    try {
        return (/^("(\\.|[^"\\\n\r])*?"|[,:{}\[\]0-9.\-+Eaeflnr-u \n\r\t])+?$/.test(this)) &&
            eval('(' + this + ')');
    } catch (e) {
        return false;
    }
};


function whichBrs() {
	var agt=navigator.userAgent.toLowerCase();
	if (agt.indexOf("firefox") != -1) return 'firefox';
	if (agt.indexOf("safari") != -1) return 'safari';
	if (agt.indexOf("msie") != -1) return 'ie';
	if (agt.indexOf('\/') != -1) {
	if (agt.substr(0,agt.indexOf('\/')) != 'mozilla') {
	return navigator.userAgent.substr(0,agt.indexOf('\/'));}
	else return 'Netscape';} else if (agt.indexOf(' ') != -1)
	return navigator.userAgent.substr(0,agt.indexOf(' '));
	else return navigator.userAgent;
}