// chemicals north west javascript

$(document).ready(function(){

		$('#tbar_structure_created').mouseup(function(){
			$('#duocmsAccessories').load(function(){
				$('#duocmsAccessories').contents().ready(function(){
					$('#duocmsAccessories').contents().find('.bluebutton a').mouseup(function(){
						var txt = $('#duocmsAccessories').contents().find('.bluebutton').html();
						txt = txt.substr(txt.indexOf("ac_setField('"));
						txt = txt.substr(txt.indexOf("'")+1);
						txt = txt.substr(0,txt.indexOf(" "));
						tmpdate2 = txt.split('-');
						newdate = '';
						newdate += tmpdate2[2]; //.replace(/^[0]+/g,"");
						newdate += "/"+tmpdate2[1]; //.replace(/^[0]+/g,"");
						newdate += "/"+tmpdate2[0]; //.replace(/^[0]+/g,"");
						$('.ecal_date[name=start]').val(newdate);
					});
				});
			});
		});
		

		$('#calEvents .ecal_date[name=start]').live('change',function(){
			//console.log('ready');
		});
			
			
		$('.calendar .daysrow .day').live('click',function(){
			var seldate = $('#calEvents .ecal_date[name=start]').val();
			tmpdate = seldate.split('/');
			newdate = '';
			newdate += tmpdate[2] + '-';
			newdate += tmpdate[1] + '-';
			newdate += tmpdate[0];
			update = $('#tbar_structure_created').val();
			update = newdate + update.substr(10);
			$('#tbar_structure_created').val(update);
		});
		
});


function textSize(s){
	var b = document.getElementsByTagName('body')[0];
	switch(s){
		case '0':
			b.style.fontSize = "0.8em";
			break;
		case '1':
			b.style.fontSize = "0.9em";
			break;
		case '2':
			b.style.fontSize = "1em";
			break;
		default:
			b.style.fontSize = "0.8em";
			break;
	}
	cookieMaker('cnwtextsize',s);
}

function initTextSize(){
	if(c=cookieVal('cnwtextsize')){
		textSize(c);
	}
}

function cookieMaker(myName,textsize){
	document.cookie=myName+'='+textsize+'; path=/';
}

function cookieVal(cookieName){
	var thisCookie=document.cookie.split("; ");
	if(thisCookie.length>0){
		for (cook=0; cook<thisCookie.length; cook++){
			if (cookieName==thisCookie[cook].split("=")[0]){
				return thisCookie[cook].split("=")[1];
			}
		}
	}
}



// slideshow fix
if(document.addEventListener){window.addEventListener("load", fixsafari, false); }else 
if(document.attachEvent){window.attachEvent("onload", fixsafari);}

function fixsafari(){
	ecal_init();
	$('.dl_gallery a').lightBox();
	var agt=navigator.userAgent.toLowerCase();
	if (agt.indexOf("safari") != -1){ 
		theObjects = document.getElementsByTagName("object");
		for (var i = 0; i < theObjects.length; i++) {
			if(theObjects[i].parentNode.className == "duoflash"){	
				for (j=0;j<theObjects[i].childNodes.length;j++){
					if(theObjects[i].childNodes[j].name=="Src"){
						var data=theObjects[i].childNodes[j].value;
					}
				}
			if(data && data.match(/slideshow.swf/i)){
				var height=theObjects[i].height;
				var width=theObjects[i].width;
				var classid=theObjects[i].classid;
				var codebase=theObjects[i].codebase;
				var htmlData = theObjects[i].parentNode.innerHTML;
				var newHtml='<object data="'+data+'" width="'+width+'" height="'+height+'" classid="'+classid+'" codebase="'+codebase+'" >  <param name="AllowFullScreen" value="true" /> <param name="WMode" value="Opaque" /></object>';
				var newObject=theObjects[i].parentNode;
				newObject.innerHTML=newHtml;
			}
			}
		}
	}
}




// blog tags
//= = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = =
/*
function duoTags_showCloud(){
	var myConn = new XHConn();
	myConn.connect("/duocms/tags/tagCloud/","POST",'',duoTags_showCloudOutput);
}

function duoTags_show(sid,mode){
	if(!mode){ mode = ''; }
	var myConn = new XHConn();
	myConn.connect("/duocms/tags/readtags/"+sid+"/"+mode+"/","POST",'',duoTags_showOutput);
}

function duoTags_showOutput(data){
	var data= data.responseText;
	document.getElementById('duoTags').innerHTML = unt8Decode(data);
}

function duoTags_showCloudOutput(data){
	var data= data.responseText;
	document.getElementById('duoTags_cloud').innerHTML = unt8Decode(data);
}

function duoTags_save(sid){
	var tagval = document.getElementById('newtag_value').value;
	if(tagval){
		if(sid){
			var myConn = new XHConn();
			myConn.connect("/duocms/tags/savetag/"+sid+"/"+tagval+"/","POST",'',duoTags_saved);
			duoTags_list(sid);
		} else {
			document.getElementById('duoTags_message').innerHTML = 'Failed to save tag';
		}
	} else {
		document.getElementById('duoTags_message').innerHTML = 'You have not entered a tag';
	}
}

function duoTags_remove(sid,tagval,tagid){
	if(tagval){
		var myConn = new XHConn();
		myConn.connect("/duocms/tags/removetag/"+sid+"/"+tagval+"/"+tagid+"/","POST",'',duoTags_removed);
	} else {
		document.getElementById('duoTags_message').innerHTML = 'Failed to remove tag';
	}
}

function duoTags_saved(data){
	var data = data.responseText;
	document.getElementById('duoTags').innerHTML = unt8Decode(data);
	document.getElementById('duoTags_message').innerHTML = 'tag saved';
}

function duoTags_removed(data){
	var data = data.responseText;
	document.getElementById('duoTags').innerHTML = unt8Decode(data);
	document.getElementById('duoTags_message').innerHTML = 'tag removed';
}

function duoTags_list(sid){
	var myConn = new XHConn();
	myConn.connect("/duocms/tags/taglist/"+sid+"/","POST",'',duoTags_listed);
}

function duoTags_listed(data){
	var data = data.responseText;
	document.getElementById('duoTags_list').innerHTML = unt8Decode(data);
}
//*/
//= = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = =




//= = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = =
// NEW blog tags stuff

function duoBlogTags(sid,editmode){
	if(sid){
		var myConn = new XHConn();
		myConn.connect("/duocms/blogtags/showtags/"+sid+"/"+editmode+"/","POST",'',duoBlogTags_refresh);
	}
}

function duoBlogTags_refresh(data){
	var data = data.responseText;
	document.getElementById('duoBlogTags_wrapper').innerHTML = data;
}

function duoBlogTags_checkbox(chk,sid,tagval,tagid,editmode){
	if(chk){
		if(chk.checked == 1){
			duoBlogTags_add(sid,tagval,editmode);
		} else {
			duoBlogTags_remove(sid,tagid,editmode);
		}
	}
}

function duoBlogTags_add(sid,tagval,editmode){
	if(sid && tagval){
		var myConn = new XHConn();
		myConn.connect("/duocms/blogtags/saveTag/"+sid+"/"+tagval+"/"+editmode+"/","POST",'',duoBlogTags_added);
	}
}

function duoBlogTags_remove(sid,tagid,editmode){
	if(tagid){
		var myConn = new XHConn();
		myConn.connect("/duocms/blogtags/removeTag/"+sid+"/"+tagid+"/"+editmode+"/","POST",'',duoBlogTags_removed);
	}
}

function duoBlogTags_added(data){
	var data = eval( "(" + data.responseText + ")" );
	if(data.success == '1'){ document.getElementById('duoBlogTags_message').innerHTML = '<p>Tag added</p>'; } else { document.getElementById('duoBlogTags_message').innerHTML = '<p>Tag NOT addedd</p>'; }
	duoBlogTags(data.sid,data.editmode);
}

function duoBlogTags_removed(data){
	var data = eval( "(" + data.responseText + ")" );
	if(data.success == '1'){ document.getElementById('duoBlogTags_message').innerHTML = '<p>Tag removed</p>'; } else { document.getElementById('duoBlogTags_message').innerHTML = '<p>Tag NOT removed</p>'; }
	duoBlogTags(data.sid,data.editmode);
	
}

//= = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = =




//calendar Stuff
//= = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = 
function cal_selDate(seldate,id){
	if(seldate){//remove from db
		var myConn = new XHConn();	
		myConn.connect("/duocms/calendar/output/"+seldate+"/"+id+"/", "POST", '', cal_showLoadedCal);
	}
}

function cal_showLoadedCal(data){
	var data=data.responseText;
	document.getElementById('eventCalDiv').innerHTML=unt8Decode(data);
}


function cal_roombook(bookdate,bookdate2,id){ 
	var cal_starttime=document.getElementById('cal_starttime').value;
	var cal_endtime=document.getElementById('cal_endtime').value;
	var cal_cost=document.getElementById('caltimeCost').innerHTML.replace(/[^0-9.]*/gi,'');
	if(confirm('Are you sure you want to book this room \nfrom '+cal_starttime+' until '+cal_endtime+" on "+bookdate2+"?")){
		var startDate=bookdate+" "+cal_starttime+":00";
		var endDate=bookdate+" "+cal_endtime+":00";
		var info=startDate+"/"+endDate+"/"+id+"/0/0/"+cal_cost;
		var myConn = new XHConn();	
		myConn.connect("/duocms/calendar/set/"+info+"/", "POST", '', cal_showLoadedCal);
	}	
}

function cal_updateTime(hourlyprice){
	var cal_starttime=document.getElementById('cal_starttime').value.split(':');
	var cal_endtime=document.getElementById('cal_endtime').value.split(':');
	var caltimeDurationH=cal_endtime[0]-cal_starttime[0];
	var caltimeDurationM=cal_endtime[1]-cal_starttime[1];
	var caltimeDuration='';
	if(caltimeDurationH){						caltimeDuration+=caltimeDurationH+" Hour";		}
	if(caltimeDurationH>1){						caltimeDuration+="s";			}
	if(caltimeDurationH && caltimeDurationM){	caltimeDuration+=" and ";						}
	if(caltimeDurationM){						caltimeDuration+=caltimeDurationM+" minutes ";	}
	document.getElementById('caltimeDuration').innerHTML=caltimeDuration;
	var price=parseFloat((caltimeDurationH+(caltimeDurationM/60))*hourlyprice); 
	document.getElementById('caltimeCost').innerHTML="£"+price.toFixed(2);
	cal_resetTicks();
}

function cal_requestCancel(evtid){
	if(confirm('Are you sure you want to cancel this booking?')){
		window.location.href='http://www.umic.co.uk/duocms/calendar/userCancel/'+evtid+'/';
	}
	
}

function cal_resetTicks(){
	var allInputs=document.getElementsByTagName('INPUT');
	for(i=0;i<allInputs.length;i++){
		if(allInputs[i].className=='bookingCheckBox'){
			allInputs[i].checked=false;
		}		
	}	
}

function cal_setTimes(obj,start,end,price){
	document.getElementById('cal_starttime').value=start;
	document.getElementById('cal_endtime').value=end;
	cal_resetTicks();
	obj.checked=true;	
	var cal_starttime=start.split(':');
	var cal_endtime=end.split(':');
	var caltimeDurationH=cal_endtime[0]-cal_starttime[0];
	var caltimeDurationM=cal_endtime[1]-cal_starttime[1];
	if(caltimeDurationM<0){
		caltimeDurationM=30;
		caltimeDurationH--;		
	}
	var caltimeDuration='';
	if(caltimeDurationH){						caltimeDuration+=caltimeDurationH+" Hour";		}
	if(caltimeDurationH>1){						caltimeDuration+="s";			}
	if(caltimeDurationH && caltimeDurationM){	caltimeDuration+=" and ";						}
	if(caltimeDurationM){						caltimeDuration+=caltimeDurationM+" minutes ";	}
	document.getElementById('caltimeDuration').innerHTML=caltimeDuration;
	document.getElementById('caltimeCost').innerHTML="£"+price;
	
}






//Event Calendar Stuff
//= = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = 

var ecaldatecount=0;


//Event Calendar Stuff
//= = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = 
function ecal_selDate(seldate){
	if(seldate){//remove from db
		var myConn = new XHConn();	
		myConn.connect("/duocms/eventcal/output/"+seldate+"/", "POST", '', ecal_showLoadedCal);
	}
}

function ecal_showLoadedCal(data){
	var data=data.responseText;
	document.getElementById('eventCalDiv').innerHTML=unt8Decode(data);
}
//calendar Stuff
//------------------------------------------------------------------------------------------
//advanced controls for events calander
function ecal_init(){
	if(document.getElementById('calEvents')){
		var loc=document.location.href;
		if(loc.match(/_duoedit/ig)){
			document.getElementById('calEvents').innerHTML='loading';
			ecal_getEvents();
		}
	}
}

function ecal_getEvents(){
	var myConn = new XHConn();
	var structure_id=document.getElementById('duocmsStructureId').value;
	myConn.connect("/duocms/eventcal/getdates/"+structure_id+"/", "POST","", ecal_getEvents_res);
}

function ecal_getEvents_res(data){
	//document.getElementById('calEvents').innerHTML=data.responseText;
	var data=eval('(' +data.responseText + ')');
	var list=document.getElementById('calEvents');
	var html='<table><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><input type="hidden" name="id" value="'+listdata[row].id+'" /><input class="ecal_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="ecal_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="ecal_delrow(this)" value=" x " title="delete this date range" /></td></tr>';	
			}
		}
	}
	html+='</tbody></table><div id="ecal_buttons"><input class="ecal_button" type="button" onclick="ecal_addDate();" value="add date range" /><input class="ecal_button" type="button" type="button" onclick="ecal_saveAllEvents()" value="save dates" /></div><div id="ecal_saving">saving</div>';
	list.innerHTML=html;	
	for(var row in listdata){
		if(listdata[row].id){
			ecal_addCals(listdata[row].id);
		}
	}	
}

function ecal_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 ecal_saveEvent(row){
	var myConn = new XHConn();
	var inputs=row.getElementsByTagName('input');
	var selects=row.getElementsByTagName('select');
	var structure_id=document.getElementById('duocmsStructureId').value;
	var id=inputs[0].value;
	var start=inputs[1].value;
	var end=inputs[2].value;
	var repeat=selects[0].value;
	var savingData="&structure_id="+structure_id+"&id="+id+"&start="+start+"&end="+end+"&repeat="+repeat;
	myConn.connect("/duocms/eventcal/updateDate/", "POST", savingData, ecal_saveEvent_res);
}

function ecal_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++){
		ecaldatecount++;
		document.getElementById('ecal_buttons').style.display='none';
		document.getElementById('ecal_saving').style.display='block';
		ecal_saveEvent(trs[i]); 
	}
}

function ecal_saveEvent_res(data){
	ecaldatecount--;
	if(ecaldatecount==0){
		document.getElementById('ecal_buttons').style.display='block';
		document.getElementById('ecal_saving').style.display='none';	
	}
}

function ecal_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='<input type="hidden" name="id" value="" /><input class="ecal_date" name="start" value="" id="f_date_'+rowcount+'"/><button type="reset" id="f_trigger_'+rowcount+'" >...</button>'; 
	cell=row.insertCell(-1); 
	cell.innerHTML='<input class="ecal_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" />';
	ecal_addCals(rowcount);
	//alert(rowcount);
}

function ecal_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
		ecaldatecount++;
		var myConn = new XHConn();	
		myConn.connect("/duocms/eventcal/deleteDate/"+id+"/", "POST", '', ecal_delrow_res);
	}
	row.parentNode.removeChild(row);	
}

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

function ecal_selDate(seldate){
	if(seldate){//remove from db
		var myConn = new XHConn();	
		myConn.connect("/duocms/eventcal/output/"+seldate+"/", "POST", '', ecal_showLoadedCal);
	}
}
function ecal_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;
}


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


