var ecaldatecount=0;

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

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

function keepAlive(){
	var myConn = new XHConn();
	myConn.connect("/duocms/orbit/", "POST","", keepAlive_res);
	setTimeout("keepAlive()",60000);//ping every minute
}

function keepAlive_res(data){
	
	
}

function fixsafari(){
	var agt=navigator.userAgent.toLowerCase();
	ecal_init();
	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.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;
			}
			}
		}
	}
	setTimeout("keepAlive()",1000);//keep logged in
}
//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;
}