// printworks javascript

    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; 

function clearInput(obj,mode,val) {
	if(!obj) {
		obj = document.getElementById('q');
	}
	if(mode == "f") {
		if(obj.value == val) {
			obj.value = "";
		}
	} else if(mode == "b") {
		if(obj.value == "") {
			obj.value = val;
		}
	}
}

function postLogin() {
	document.loyaltylogin.password.value=hex_md5(hex_md5(document.getElementById('loyaltypass').value)+document.loyaltylogin.pass_hash.value);
	document.loyaltylogin.pass_hash.value='';
	document.loyaltylogin.submit();
	return(false);
}

function offers_filler() {
	var ul = document.getElementById('offersul2');
	var kids = ul.getElementsByTagName('li');
	var remainder = (kids.length - 3) % 4;
	if(remainder > 0) {
		document.getElementById('offers_filler1').style.display = "block";
		if(remainder < 3) {
			document.getElementById('offers_filler2').style.display = "block";
		}
		if(remainder == 1) {
			document.getElementById('offers_filler3').style.display = "block";
		}
	} else {
		return false;
	}
}



function getElementsByClassName(object,name){
	var allNodes=object.getElementsByTagName('*');
	if(!allNodes){
		var allNodes=object.all;	
	}
	var returnObj=new Array;
	var count=0;
	for(var i=0;i<allNodes.length;i++){
		if(allNodes[i].className.replace(name,"")!=allNodes[i].className){
			returnObj[count]=allNodes[i];
			count++;
		}
	}
	return returnObj;
}



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

function competitionTools(){
	if(document.getElementById('competitionControls') && document.getElementById('columna')){
		var toolbar=document.getElementById('competitionControls');
		toolbar.innerHTML='<div class="competionAddButton"><a onclick="javascript:void(competitionAddQuestion())">add question</a></div>';		
		var total=0;
		var formArea=document.getElementById('competitionAdd');
		var val='';
		var html='<div id="competitionAddInner">'
		while(document.getElementById('compquestion'+total)){
			val=document.getElementById('compquestion'+total).innerHTML;
			html+='<div id="quesinput'+total+'"><a onclick="compQuestionRemove(\'quesinput'+total+'\')">x</a><input onkeyup="competitionCreateForm()" type="text"  value="'+val+'" /></div>';
			total++;
		}
		html+="</div>";
		formArea.innerHTML=html;
		var competitionArea=document.getElementById('columnd');
		competitionArea.setAttribute('contentEditable',false);
		document.getElementById('compQuestions').style.display="none";
	}
}

function competitionAddQuestion(){
	var formArea=document.getElementById('competitionAddInner');
	var inputs=formArea.getElementsByTagName('INPUT');
	var total=inputs.length+1;
	formArea.innerHTML+='<div id="quesinput'+total+'"><a onclick="compQuestionRemove(\'quesinput'+total+'\')">x</a><input onkeyup="competitionCreateForm()" type="text" value="'+total+'. your question here" /></div>';
	/*
	
	var formArea=document.getElementById('columna');
	//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+'" />';
	*/
}

function compQuestionRemove(id){
	//alert(id);return;
	document.getElementById(id).outerHTML='';
	competitionCreateForm();
}

function competitionCreateForm(){
	var formArea=document.getElementById('competitionAdd');
	var competitionArea=document.getElementById('columnd');
	var inputs=formArea.getElementsByTagName('INPUT');
	var html='';
	for(var i=0;i<inputs.length;i++){
		html+='<div><label id="compquestion'+i+'">'+inputs[i].value+'</label><input class="fullWidth" name="answer'+i+'" /></div>';		
	}
	competitionArea.innerHTML=html;
}

//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);	
	}
}


var validcaptcha = false;

function competitionValidateAndSendTest(){
	
	//check user info form - the question answers are optional
	var form=document.getElementById('competform'); 	
	var field='';
	var errorcount=0;
	var question='';

	var qVal
	var answerInputs = getElementsByClassName(document,'fullWidth');
	for(var x=0;x<answerInputs.length;x++){
		qVal = answerInputs[x].value;
		if(qVal.length < 1){
			answerInputs[x].style.border = "1px solid #f00";
			errorcount++;
		} else {
			answerInputs[x].style.border = "1px solid #cccccc";
		}
	}

	var formFields=form.getElementsByTagName('INPUT');
	var formTextArea = document.getElementById('comp_address');
	for(var i=0;i<formFields.length;i++){
		field=formFields[i];
		if(field.value.length<1){
			field.style.border="1px solid red";
			errorcount++;
		}else{
			field.style.border="1px solid #cccccc";
		}
	}
	if(formTextArea.value.length<1) {
		formTextArea.style.border = "1px solid #f00";
		errorcount++;
	} else {
		formTextArea.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{
		
		if(!validcaptcha){
			competitionCaptcha();
		} 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"){
					
					if(document.getElementById(('compquestion'+field.name.replace('answer','')))){
						question=document.getElementById(('compquestion'+field.name.replace('answer',''))).innerHTML.replace(/[\n\r\t]*/,'');
					}else{
						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);	
		}
//		alert(savingData);

	}
}

function competitionCaptcha(){
	var savingData = "captcha_code="+document.getElementById('captcha_code').value;
	var myConn = new XHConn();
	myConn.connect("/secureimage/captchacheck.php","POST",savingData,captchaDone);	
}

function captchaDone(data){
	if(data.responseText == "1"){
		validcaptcha = true;
		competitionValidateAndSendTest();
	} else {
		document.getElementById('captchaFeedback').innerHTML = "Captcha code incorrect. Please try again.";
	}
}




function competitionValidateAndSendTestNew(){
	
	var doctitle = document.title;
	if(doctitle.match("news")){
		var isnewsletter = doctitle.match("news");
	}
	
	//check user info form - the question answers are optional
	var form=document.getElementById('competform'); 	
	var field='';
	var errorcount=0;
	var question='';

	var qVal
	var answerInputs = getElementsByClassName(document,'fullWidth');
	for(var x=0;x<answerInputs.length;x++){
		qVal = answerInputs[x].value;
		if(qVal.length < 1){
			answerInputs[x].style.border = "1px solid #f00";
			errorcount++;
		} else {
			answerInputs[x].style.border = "1px solid #cccccc";
		}
	}

	var formFields=form.getElementsByTagName('INPUT');
	var formTextArea = document.getElementById('comp_address');
	for(var i=0;i<formFields.length;i++){
		field=formFields[i];
		if(field.value.length<1){
			field.style.border="1px solid red";
			errorcount++;
		}else{
			field.style.border="1px solid #cccccc";
		}
	}
	if(formTextArea.value.length<1) {
		formTextArea.style.border = "1px solid #f00";
		errorcount++;
	} else {
		formTextArea.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{
		
		if(!validcaptcha){
			competitionCaptchaTestNew();
		} else {
			//submit all form data
			formFields=form.elements;
			if (isnewsletter) {
				var savingData = 'func=newsletter&';
			}
			else {
				var savingData = '';
			}
			var theval='';
			for(var i=0;i<formFields.length;i++){
				field=formFields[i];
				if(field.name){
					if(field.name.substr(0,3) == "GP_"){
						if(field.checked == 1){
							theval = "yes";
						} else {
							theval = field.value;
						}
					} else {
						theval = field.value;
					}
						savingData+=field.name+"="+theval+"&";
					
				}
			}
			//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("/comp_test.php", "POST", savingData, competitionRedirect);	
		}
//		alert(savingData);

	}
}

function competitionCaptchaTestNew(){
	var savingData = "captcha_code="+document.getElementById('captcha_code').value;
	var myConn = new XHConn();
	myConn.connect("/secureimage/captchacheck.php","POST",savingData,captchaDoneTestNew);	
}

function captchaDoneTestNew(data){
	if(data.responseText == "1"){
		validcaptcha = true;
		competitionValidateAndSendTestNew();
	} else {
		document.getElementById('captchaFeedback').innerHTML = "Captcha code incorrect. Please try again.";
	}
}





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=unt8Decode(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;
}

function unt8Decode(s){
		var str = s.split("");
		var l = str.length;
		for(var i=0;i<l;i++){
			if(str[i].charCodeAt(0) >= 127){
				str[i]='&#'+str[i].charCodeAt(0)+';';
			}
		}
		return str.join("");
		//return s;

}

