// Rivisat_ajax.js
//  Created on Mar 30, 2007
// @author     Habes Alkhraisat <hma@jensentechnologies.com>

node_array=  new Array();
label_array= new Array();
errorflag=0;


var RivistaAjax = {
	result:false,
	url:"/core/ajaxserver.php?sid=" + new Date().getTime(),
	ER:"We're so sorry, the server is busy right now please try again",	
	iconon_array :new Array(),
	iconoff_array: new Array(),
	asynchronous:false,
	doAjaxCall:function(params,method,callback){
		var myAjax = new Ajax.Request(
      	this.url,
      	{
        method: method,
        parameters: params,
        asynchronous:this.asynchronous,
        setrequestheaders:['Cache-Control: no-store, no-cache, must-revalidate','Accept-Encoding: compress, gzip'],
        onfailure:function(){alert(this.ER);},
        onComplete: callback
      });
	},
	doToggleField: function(node,params,label,iconon,iconoff,confirmMsg,forcePageReload) {

		// display an optional confirm message
		if(confirmMsg) {
			if(!confirm(confirmMsg)) {
				return false;
			}
		}
		label_array.push(label);
	node_array.push(node);
	params = "req=toggle&"+params;
	RivistaAjax.iconon_array.push(iconon);
	RivistaAjax.forcePageReload=forcePageReload;
	RivistaAjax.iconoff_array.push(iconoff);
	node.childNodes[0].src = "/admin/media/images/ajax-loader.gif";
	RivistaAjax.doAjaxCall(params,"GET",RivistaAjax.doToggleField_handler);
	},
	doToggleField_handler:function(transport){
		if (transport.readyState == 4 && transport.status == 200){
			if(transport.responseText){
   		 	node_t = node_array.shift();
 			iconon=RivistaAjax.iconon_array.shift();
			iconoff=RivistaAjax.iconoff_array.shift();
			label_t = label_array.shift().split('|');
	       	if(transport.responseText.trim()=='f'){
	        		node_t.childNodes[0].src = '/admin/media/images/' + iconoff;	
	        		node_t.childNodes[0].alt= label_t[0];
	        		node_t.childNodes[0].title= label_t[0];
	        		RivistaAjax.changeAllRelated(node_t.childNodes[0].src,node_t.childNodes[0].id,label_t[0]);
			} else{
					node_t.childNodes[0].src = '/admin/media/images/' + iconon;
					node_t.childNodes[0].alt= label_t[1];
					node_t.childNodes[0].title= label_t[1];
					RivistaAjax.changeAllRelated(node_t.childNodes[0].src,node_t.childNodes[0].id,label_t[1]);
				}
	        	if(RivistaAjax.forcePageReload) {
	        		window.location.reload();
	        	}
			}
		}
},
	changeAllRelated:function(imgsrc,id,n_label){
  			var imgs;
		  	imgs =document.getElementsByTagName('img');
		  	for (i=0;i<imgs.length;i++)
				if(imgs[i].id==id && !(id=='')){
					imgs[i].src = imgsrc;
					imgs[i].alt=n_label;
					imgs[i].title=n_label;
				}
		},
	increaseViews: function(params,id) {
			params = "req=increaseviews&field="+params+"&id="+id;
			RivistaAjax.doAjaxCall(params,"GET",RivistaAjax.increaseViews_handler);
  		},
  	increaseViews_handler:function(transport){},


  		checkEmail:function(fld,id) {
	  	    errorflag=0;
			if($F(fld)=='' || $F(fld).trimAll=='') {

				alert('The Email field cannot be left blank.');
		     	        errorflag=1;
				return false;
			}
	   		params = "req=checkEmail&email="+escape($F(fld))+"&id="+id;
	   		RivistaAjax.doAjaxCall(params,"GET",RivistaAjax.checkEmail_handler);
  		},


  		checkEmail_handler:function(transport){
        	if(transport.responseText.trim()=='f'){
        		alert('The email address you specified already exists.');
				fld.focus();
				errorflag=1;
				} else{
					alert('The email address seems to be ok!');
					return;
				}
  		},
  	checkScreenname:function(fld,id) {
  	    errorflag=0;
		if($F(fld)=='' || $F(fld).trimAll==''){
			return true;
		}
		params = "req=checkScreenname&screenname="+escape($F(fld))+"&id="+id;
		RivistaAjax.doAjaxCall(params,"GET",RivistaAjax.checkScreenname_handler);
  		},
  	checkScreenname_handler:function(transport){
  		if(transport.responseText){
       	if(transport.responseText=='f'){
       			alert('That screen name is in use.  Please choose another.');
		  	    errorflag=1;
			fld.focus();
			} else{
				alert('That screen name seems ok!');
				return;
			}
  		}
  	},	
  	getGeobaseListings:function(geobaseid,search,initOptions) {
   		params = "req=getGeobaseListings&geobaseid="+escape(geobaseid)+'&search='+escape(search);
	   	var options = initOptions || {};
    	if(options.zipcodes) {
    	    var zipcodes = options.zipcodes.replace(/[^0-9,]/g,""); //strip out text
            if(zipcodes) params = params + "&zipcodes=" + escape(zipcodes);
        }
		RivistaAjax.doAjaxCall(params,"GET",RivistaAjax.getGeobaseListings_handler);
  	},
  	getGeobaseListings_handler:function(transport){
		if(transport.responseText){
			// incoming data is json encoded
			//geobasedata=transport.responseText;
			if(window.listingscallback)
				listingscallback(transport.responseText);
        }
	},
	getGeobaseListing:function(listingid) {
   		params = "req=getGeobaseListing&listingid="+escape(listingid);
   		RivistaAjax.doAjaxCall(params,"GET",RivistaAjax.getGeobaseListing_handler);
	},
	getGeobaseListing_handler:function(transport){
		if(transport.responseText){
			// incoming data is json encoded
			//geobasedata=transport.responseText;
			if(window.getGeobaseListingCallback)
				getGeobaseListingCallback(transport.responseText);
		}
	},
	opsCalendarLoadEvent:function(eventID,calendarID){
		if(RivistaAjax.doShowHideEvent(eventID,calendarID)) {
			return;
		}
		var calendar = $('calendar_' + calendarID);
		params = "req=getCalendarEvent&eventid="+escape(eventID)+"&calendarid="+escape(calendarID);
		calendar.getElementsByClassName('ajaxloader')[0].style.display = 'block';
   		RivistaAjax.doAjaxCall(params,"GET", function(transport) {
   			RivistaAjax.opsCalendarLoadEvent_handler(transport, calendar);
   		});
   		RivistaAjax.doShowHideEvent(eventID,calendarID);
	},
	opsCalendarLoadEvent_handler:function(transport, calendar){
		if(transport.responseText){
			calendar.getElementsByClassName('ajaxloader')[0].style.display = 'none';
			calendar.getElementsByClassName('eventContainer')[0].update(transport.responseText);
		}
	},
	doShowHideEvent:function(eventID, calendarID){
		var calendar = $('calendar_' + calendarID);
		var eventsContainer = calendar.getElementsByClassName('eventsContainer')[0];
		var eventContainer = calendar.getElementsByClassName('eventContainer')[0];
		if($('event_'+eventID) != null) {
			Effect.ScrollTo(calendar, {offset: -15});
			if(eventContainer.style.display == 'none'){
				eventsContainer.style.display = 'none';
				eventContainer.style.display = 'block';
				return true;
			} else {
				eventsContainer.style.display = 'block';
				eventContainer.style.display = 'none';
				return true;
			}
		} 
		return false;		
	},
	
	bindCalendarEvents: function(calendarID) {
		var calendar = document.getElementById('calendar_' + calendarID);
		Event.observe(calendar, 'click', function(e) {
			var node = Event.element(e); // find element actually clicked on, in event delegation fashion
			if (node.nodeName == 'A') { // in case of A elements (links) ...
				if (node.className.search('load_calendar') > -1) { // ok, we've landed on something interesting: an anchor with a className that includes 'load_calendar'... so load the calendar.
					Event.stop(e); // prevent default browser action
					$$('#calendar_' + calendarID + ' .mini_view td a').each(function(day, index) {
						day.parentNode.className = (day == node) ? 'currentday' : 'eventday'; // highlight the day we clicked, blur the others
					});
					var dateMembers = node.getAttribute('calendar_request_date').split(':');
					var calendarView = node.getAttribute('calendar_view');
					var calendarTemplate = node.getAttribute('template');
					var calendarCategory = this.getAttribute('calendar_category'); // 'this' refers to the calendar root node
					RivistaAjax.loadCalendar(
						calendarID
						, parseInt(dateMembers[0], 10)
						, parseInt(dateMembers[1], 10)
						, parseInt(dateMembers[2], 10)
						, calendarView
						, calendarCategory
						, calendarTemplate
					);
				}
			}
		});
	},
	loadCalendar:function(calendarID, y, m, d, view, filter, template){
		//console.log('loadCalendar')
		var calendar = document.getElementById('calendar_' + calendarID);
		params ='req=getCalendar&view='+view+'&m='+m+'&y='+y+"&d="+d+"&calid="+escape(calendarID)+"&categoryfilter="+escape(filter)+"&template="+template;
		calendar.getElementsByClassName('eventContainer')[0].style.display = 'none'; // hide() wasn't available via $$, confusing...
		calendar.getElementsByClassName('ajaxloader')[0].style.display = 'block'; // show() wasn't available via $$, confusing...
   		RivistaAjax.doAjaxCall(params,"GET",RivistaAjax.loadCalendar_handler);
	},
	loadCalendar_handler:function(transport){
		var calendarID = transport.request.parameters.calid;
		var currentDay = transport.request.parameters.d;
		var calendar = document.getElementById('calendar_' + calendarID);
		if (transport.request.parameters.view == 'day_view') {
			$$('#calendar_' + calendarID + ' .eventsContainer')[0].innerHTML = transport.responseText;
		}
		else {
			calendar.replace(transport.responseText);
		}
		calendar.getElementsByClassName('eventsContainer')[0].style.display = 'block';
		calendar.getElementsByClassName('ajaxloader')[0].style.display = 'none';
	}
}

