// umic javascript

var ncicalinit = false;
var lastFullSearch='';
var lastFullSearchString='';

$(document).ready(function () {

	$('span.booked').live('mouseenter',function(){
		$(this).children('div.hoverinfo').show();
	}).live('mouseleave',function(){
		$(this).children('div.hoverinfo').hide();
		if($.browser.safari || $.browser.webkit){
			$('#eventCalDiv').html($('#eventCalDiv').html());
		}
	});

	nci_calInit();
	
	tenantsetup();
	
	$('.datepicker').each(function(){
		$(this).datepicker();
	});
	
	$('.booked').live('mouseover mouseout',function(event){
		if(event.type == 'mouseover'){
			$(this).addClass('bookedover');
		} else {
			$(this).removeClass('bookedover');
		}
	});

			if($('#kwhightech').length>0){
				var keywords = $('#tbar_pages_keywords').val();
				if(keywords.match("kwhightech")){
					$('#kwhightech').attr('checked',true);
				}else{
					$('#kwhightech').attr('checked',false);
				}
				if(keywords.match("kwbiotech")){
					$('#kwbiotech').attr('checked',true);
				}else{
					$('#kwbiotech').attr('checked',false);
				}
				if(keywords.match("kwconferencing")){
					$('#kwconferencing').attr('checked',true);
				}else{
					$('#kwconferencing').attr('checked',false);
				}
			}
			$('.keywordClick').click(function(event){
				//remove from keywords
				var keywords = $('#tbar_pages_keywords').val();
				keywords=keywords.replace(" "+event.target.id,'');
				if(event.target.checked){//if true add to keywoards 
					keywords=keywords+" "+event.target.id;
				}
				$('#tbar_pages_keywords').val(keywords);
			});
			
			var panels = $('.fppanel');
			var $container = $('#fpscrollContainer');
			if($container.length==0){return;}
			var horizontal = true;
			if (horizontal) {
			  panels.css({
			    'float' : 'left',
			    'position' : 'relative' // IE fix to ensure overflow is hidden
			  });
			  $container.css('width', panels[0].offsetWidth * panels.length);
			}
			var $scroll = $('#fpshow');
			
			// handle nav selection
			function selectNav() {
			  $(this)
			    .parents('ul:first')
			      .find('a')
			        .removeClass('selected')
			      .end()
			    .end()
			    .addClass('selected');
			}
			
			$('#fpshowButtons').find('a').click(selectNav);
			
			// go find the navigation link that has this target and select the nav
			function trigger(data) {
			  var el = $('#fpshowButtons').find('a[href$="' + data.id + '"]').get(0);
			  selectNav.call(el);
			}
			
			if (window.location.hash) {
			  trigger({ id : window.location.hash.substr(1) });
			} else {
			  $('#fpshowButtons a:first').click();
			}
			
			// offset is used to move to *exactly* the right place, since I'm using
			// padding on my example, I need to subtract the amount of padding to
			// the offset.  Try removing this to get a good idea of the effect
			var offset = parseInt((horizontal ? 
			  $container.css('paddingTop') : 
			  $container.css('paddingLeft')) 
			  || 0) * -1;
			
			
			var scrollOptions = {
			  target: $scroll, // the element that has the overflow
			  
			  // can be a selector which will be relative to the target
			  items: panels,
			  
			  navigation: '#fpshowButtons a',
			  
			  // selectors are NOT relative to document, i.e. make sure they're unique
			  //prev: 'img.left', 
			 // next: 'img.right',
			  
			  // allow the scroll effect to run both directions
			  axis: 'xy',
			  
			  onAfter: trigger, // our final callback
			  interval:4000,
			  offset: offset,
			  constant:false,
			  // duration of the sliding effect
			  duration: 500,
			  force:true,
			  lock:true,
			  
			  // easing - can be used with the easing plugin: 
			  // http://gsgd.co.uk/sandbox/jquery/easing/
			  easing: 'swing'
			};

			$('#fpshow').serialScroll(scrollOptions);
			$.localScroll(scrollOptions);
			//scrollOptions.duration = 1;
			$.localScroll.hash(scrollOptions);
		
			/*
			var index = 2;
			setInterval(function() {//scroll each 1
          		
       		}, 4000);
			*/

	
	$('#blackout').css('opacity','0.5');//fadeTo( 500, '0.5');
	$('#blackout').click(function(){
		hideVideo();
	});
	$('#closebutton').click(function(){
		hideVideo();	
	});
	
	$('#vidobject img').live('click',function(){
		playVideo($('#vidobject_url').val());
	});
	
	$('#vidlink img').click(function(){
		$('#vidbits').fadeIn(500,function(){
			$('#vidobject').fadeIn();
		});
	});


});


var vidHTML;

function playVideo($url){

	vidHTML = $('#vidobject').html();

	if($url){
		var obj = '<object width="640" height="388"><param name="movie" value="http://www.youtube.com/v/'+$url+'"</param><param name="allowFullScreen" value="true"></param><param name="allowScriptAccess" value="always"></param><embed src="http://www.youtube.com/v/'+$url+'" type="application/x-shockwave-flash" allowfullscreen="true" allowscriptaccess="always" width="640" height="388"></embed></object>';
		$('#vidobject').html(obj);
	}
}


function hideVideo(){
	$('#vidobject').fadeOut(500,function(){
		$('#vidbits').fadeOut();
		$('#vidobject').html(vidHTML);
		/*$('#closebutton').animate({top:-420},500);
		$('#vidoverlay').animate({top:-420},500,function(){
			$('#vidbits').fadeOut();
			$('#vidoverlay').remove();
		});*/
	});
}




var ecaldatecount=0;

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

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





function booking_updateNames(num){
	if(num.length > 0 && num > 0){
		if(num > 10){
			num = 10;
		}
		var dd = document.getElementById('event_names_dd');
		//dd.innerHTML = '';
		var namesArray = new Array();
		var inp;
		var br;
		var id;
		var inpArray = new Array();
		for(var i=0;i<num;i++){
			id = 'event_names_'+i.toString();
			if(document.getElementById(id)){
				namesArray[i] = document.getElementById(id).value;
			} else {
				namesArray[i] = '';
			}
			inp = document.createElement('INPUT');
//			if(i == 0){
//				inp.setAttribute('readonly','readonly');
//			}
			inp.value = namesArray[i];
			inp.id = 'event_names_'+i;
			inp.name = inp.id;
			inpArray[i] = inp;
		}
		dd.innerHTML = '';
		for(i=0;i<num;i++){
			dd.appendChild(inpArray[i]);
			br = document.createElement('BR');
			dd.appendChild(br);
		}
	}
}


//calendar Stuff
//= = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = 

function nci_calInit(){
	var d = $('#caldatehidden').html();
	var s = $('#pagestruct').html();
	nci_cal_selDate(d,s);
}


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 nci_cal_selDate(seldate,id){
	if(seldate){
		/*var myConn = new XHConn();
		myConn.connect("/duocms/calendar/outputNciCal/"+seldate+"/"+id+"/","POST",'',cal_showLoadedCal);
		*/
		$.ajax({
			type: "POST",
			url: "/duocms/calendar/outputNciCal/"+seldate+"/"+id+"/",
			success: function(msg){
				nci_calShowBookings(msg,seldate,id);
				
				/*	$tag = $(this);
					$.ajax({
						type: "POST",
						dataType: "json",
						url: "/duocms/calendar/outputNciBookings/"+$tag.html()+"/"+seldate+"/",
						success: function(msg){
							console.log('#nci_date_'+$tag.html()); //.append(msg.info.company);
						}
					});
				});*/
			}
		});
	}
}

function nci_calShowBookings(data,seldate,id){
	var dd;
	var comp;
	var compshort;
	var begin;
	var top;
	$('#eventCalDiv').html(data);
	$dates = '';
	$('#eventCalDiv a.nci_date').each(function(){
		$dates += $(this).html()+"|";
	});
	$dates = $dates.substr(0,$dates.length-1);
	$.ajax({
		type: "POST",
		dataType: "json",
		url: "/duocms/calendar/outputNciBookings/"+seldate+"/"+id+"/",
		success: function(msg){
			$.each(msg.info,function(){
				$email = this.email;
				$.each(this, function(k, v) {
					switch(k){
						case "displaydate":
							dd = v;
							break;
						case "company":
							comp = v;
							if(!comp){ comp = $email; }
							compshort = comp.substr(0,10) + '...';
							break;
						case "start_dt":
							start = v;
							start_dt = mysqlTimeStampToDate(start);
							start_ts = HumanToEpoch2(start_dt);
							slist = start.split(" ");
							begin = slist[0]+' 08:30:00';
							begin = mysqlTimeStampToDate(begin);
							begin = HumanToEpoch2(begin);
							top = start_ts - begin;
							start = slist[1].substr(0,slist[1].length-3);
							break;
						case "end_dt":
							end = v;
							end_dt = mysqlTimeStampToDate(end);
							end_ts = HumanToEpoch2(end_dt);
							elist = end.split(" ");
							end = elist[1].substr(0,elist[1].length-3);
							break;
					}
				});
				var diff = end_ts - start_ts;
				var wholeday = (60*60)*10;
				//console.log((diff/wholeday)*100 + "%");
				if(comp != 'Gentronix Ltd'){
					$('#nci_date_'+dd).append('<span class="booked" style="top:'+((top/wholeday)*100)+'%;min-height:'+((diff/wholeday)*100)+'%">'+start+'-'+end+' - '+compshort+'<div class="hoverinfo">'+start+' - '+end+' - '+comp+'</div></span>');
				}
			});
		}
	});
}

function cal_showLoadedCal(data){
	var data=data.responseText;
	document.getElementById('eventCalDiv').innerHTML=unt8Decode(data);
	if($('.calMessageBox').html().length>0){
		alert($('.calMessageBox').text());	
	}
	nci_calInit();
}


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;
//		alert(info);
		var myConn = new XHConn();	
		myConn.connect("/duocms/calendar/set/"+info+"/", "POST", '', cal_showLoadedCal);
	}	
}

function nci_cal_roombook(){
	var bookdate = $('#bookingdate').val();
	var id = $('#pagestruct').html();
	if(!bookdate){
		alert("You have not seleted a date for your booking");
	} else {
		//var bookdate2 = bookdate;
		var datesplit = bookdate.split("/");
		bookdate = datesplit[2]+"-"+datesplit[0]+"-"+datesplit[1];
		bookdate2 = datesplit[1]+"/"+datesplit[0]+"/"+datesplit[2];
		var cal_starttime = $('#cal_starttime_hour').val() + ":" + $('#cal_starttime_min').val();
		var cal_endtime = $('#cal_endtime_hour').val() + ":" + $('#cal_endtime_min').val();
		//var cal_endtime=document.getElementById('cal_endtime').value;
		var cal_cost='0.00'; //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;
			//alert(info);
			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 nci_cal_updateTime(hourlyprice){
	var cal_starttime = new Array($('#cal_starttime_hour').val(),$('#cal_starttime_min').val());
	var cal_endtime = new Array($('#cal_endtime_hour').val(),$('#cal_endtime_min').val());
	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
//= = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = 
function ecal_selDate(seldate,id){
	if(seldate){//remove from db
		var myConn = new XHConn();	
		myConn.connect("/duocms/eventcal/output/"+seldate+"/"+id+"/", "POST", '', ecal_showLoadedCal);
	}
}

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

//------------------------------------------------------------------------------------------
//advanced controls for events calander
function ecal_init(){
	if(document.getElementById('calEvents')){
		var loc=document.location.href;
		if(loc.match(/_duoEdit/ig)){	
			ecal_getEvents();
		}
	}
}

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

function ecal_getEvents_res(data){
	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=window.parent.structureid;
	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='<form><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" /></form>';
	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();	
		var savingData="func=deleteDate&id="+id;
		myConn.connect("/events.php", "POST", savingData, 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);
}



// TENANT STUFF
//= = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = 

//window.onload=mmnsetup;

function tenantsetup(){
//	console.log('tenant setup');
	if(document.getElementById('tenantupdater')){
//		if(document.getElementById('pages|html|p_0')){
		var loc=document.location.href;
		if(loc.match(/_duoEdit/ig)){
			//write keyword form
			var myConn = new XHConn();
			myConn.connect("/site-resources/javascript/search-keywords.csv", "GET", "", tenantMakeTicks);				
		}	
	} 
	if(document.getElementById('tenantSearchDialogue')){
		//write keywords search form
		var myConn = new XHConn();
		myConn.connect("/site-resources/javascript/search-keywords.csv", "GET", "", tenantAdvancedSearch);	
	}
} 

function tenantMakeTicks(data){
	var keywords=window.parent.document.getElementById('tbar_pages_keywords').value;
	var mmn_trup=document.getElementById('tenantupdater');
	var csv="\n"+data.responseText.replace(/^\s+|\s+$/, '');
	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>";
		}
		var keycount=keywords.split(keyword);
		if(keycount.length>1){
			html+="<input type='checkbox' id='"+keyword+"' onclick='tenantKeywords(\""+keyword+"\",this);' checked /><label>"+label+"</label><br />";
		}else{
			html+="<input type='checkbox' id='"+keyword+"' onclick='tenantKeywords(\""+keyword+"\",this);' /><label>"+label+"</label><br />";
		}
		prevsection=section;
	}
	mmn_trup.innerHTML=html;
}

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

function tenantAdvancedSearch(data){
	var mmnkeyterms;
	var mmnsearch=document.getElementById('tenantSearchDialogue');
	var csv="\n"+data.responseText.replace(/^\s+|\s+$/, '');
	var rows=csv.split("\n");
	
	if(document.getElementById('tenantupdater')){
		var html='<div id="advancedsearchform"><input type="text" name="searchterm" id="searchterm" onkeyup="if ((event.which && event.which == 13) || (event.keyCode && event.keyCode == 13)) { document.getElementById(\'advsearchstring\').value=document.getElementById(\'searchterm\').value;document.getElementById(\'advsearch\').submit();}" onblur="if(this.value==\'\'){this.value=\'keyword search\';}" onclick="if(this.value==\'keyword search\'){this.value=\'\';}" value="keyword search" /><input type="button" value="&gt;" onclick="document.getElementById(\'advsearchstring\').value=document.getElementById(\'searchterm\').value;document.getElementById(\'advsearch\').submit();" id="searchString_submit" />';
	} else {
		var html='<div id="advancedsearchform"><input type="text" name="searchterm" id="searchterm" onkeyup="tenantGetSearchCount();" onblur="if(this.value==\'\'){this.value=\'keyword search\';}" onclick="if(this.value==\'keyword search\'){this.value=\'\';}" value="keyword search" /><input type="button" value="&gt;" onclick="javascript:document.getElementById(\'advancedsearchform\').submit();" id="searchString_submit" />';
	}
	
	var seccount=0;
	if(mmnkeyterms){
		var mmnkeyarray=mmnkeyterms.split(" ");	
	}
	var prevsection='';
	
	var section;
	var label;
	var keyword;
	
	for (i=0;i<rows.length;i++){
		var cols=rows[i].split(";");
		if(cols.length > 2){
			section=cols[0];
			label=cols[1];
			keyword=cols[2];
			keyword = keyword.replace(/^\s+|\s+$/g, '');

			if(section!=prevsection){
				if(prevsection){
					html+="</select>";	
				}			
				//html+="<label>"+section+"</label>";
				if(document.getElementById('tenantupdater')){
					html+='<select onchange="var selIndex=this.selectedIndex;document.getElementById(\'advsearchstring\').value=this.options[selIndex].value;document.getElementById(\'advsearch\').submit();" id="kw'+seccount+'">';
				} else {
					html+="<select onchange='tenantGetSearchCount();' id='kw"+seccount+"'>";
				}
				html+="<option value=''>search by "+section+"</option>";
				seccount++;
			}
			prevsection=section;
			var kwchosen="";
			if(mmnkeyterms){
				for(j=0;j<mmnkeyarray.length;j++){
					if(mmnkeyarray[j].replace(/^\s+|\s+$/,'')==keyword){
						kwchosen="selected";	
					}
				}		
			}
			html+="<option "+kwchosen+" value='"+keyword+"'>"+label+"</option>";
		}
		
	} 
	html+="</select></div>";	
	html+="<form method='post' action='/tenant/' id='tenantsearchform'><input type='hidden' name='searchString' id='tenantsearchterm' /><form><div id='searchCount'></div></div>";
	html+="</select>";	
	html+="<div id='searchCount'></div></div>";
	mmnsearch.innerHTML=html;  
}


function mmnMakesearch(){
	var mmnsearch=document.getElementById('tenantSearchDialogue');
	var selects=mmnsearch.getElementsByTagName('SELECT');
	var keyterms='';
	for(i=0;i<selects.length;i++){
		if(selects[i].value){
			keyterms+=selects[i].value+" ";	
		}		
	}	
	document.getElementById('tenantsearchterm').value=keyterms;
	document.getElementById('tenantsearchform').submit();
}


function tenantGetSearchCount(force){
	
	var mmnsearch=document.getElementById('tenantSearchDialogue');
	var selects=mmnsearch.getElementsByTagName('SELECT');
	var qstring='';
	for(i=0;i<selects.length;i++){
		if(selects[i].value){
			qstring+=selects[i].value+" ";
		}		
	}
//	console.log(qstring);
	if(document.getElementById('searchterm').value != 'keyword search'){
		qstring+=document.getElementById('searchterm').value;
	}
	
	var qstring2='';
	if(document.getElementById('ajaxpagenum')){
		qstring2 += "&thispage="+document.getElementById('ajaxpagenum').value;
	} else {
		qstring2 += "&thispage=0";
	}
	
	//alert(qstring);
	if((lastFullSearch==qstring && lastFullSearchString!=qstring) || force){
		lastFullSearchString=qstring;	
		var myConn = new XHConn();
		myConn.connect("/site-resources/tenantsearch.php", "POST", "searchString="+qstring+qstring2, tenantGetSearchCount_res);	
		document.getElementById('tenantLiveSearch').innerHTML="Counting results...";
		lastFullSearchString=qstring;
		lastFullSearch='';
	}
	if(lastFullSearch!=qstring && !force){
		lastFullSearch=qstring;
		setTimeout(tenantGetSearchCount,1000);	
	}
}

function tenantGetSearchCount_res(data){
	var message=data.responseText;
	document.getElementById('tenantLiveSearch').innerHTML=message;	
}

//============================================================================================
/** 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;
}



function mysqlTimeStampToDate(timestamp) {
	//function parses mysql datetime string and returns javascript Date object
	//input has to be in this format: 2007-06-05 15:26:02
	var regex=/^([0-9]{2,4})-([0-1][0-9])-([0-3][0-9]) (?:([0-2][0-9]):([0-5][0-9]):([0-5][0-9]))?$/;
	var parts=timestamp.replace(regex,"$1 $2 $3 $4 $5 $6").split(' ');
	return new Date(parts[0],parts[1]-1,parts[2],parts[3],parts[4],parts[5]);
}

function HumanToEpoch2(datein){
	var datum = datein;
	return datum.getTime()/1000.0;
}




