
function AjaxWait(id, msg_pos) {

    this.id = id;
    this.error = false;

    if(msg_pos){
            this.msg_pos = msg_pos;
    } else{
            this.msg_pos = "top";
	}

    // if the AJAX objects don't exist then flag the error
    if($('ajaxWait_' + id)) {

		this.target = $(id + "_top");
        this.wrapper = $('ajaxWait_' + id);
        this.blinder = $('ajaxBlinder_' + id);
        this.temp = $('ajaxTemp_' + id);
        this.msg = $('ajaxMsg_' + id);

        this.msg.className = "ajaxMsg " + this.msg_pos;
    } else {
        this.error = true;
    }

    // fades the content out to 90% and displays the waiting msg...
    this.start = function() {
        // makes sure the AjaxWait start method doesn't re-load the ajax spinner if it's already visible...
        if(this.blinder.style.display == "none") {
            new Effect.Appear(this.blinder.id, {duration:0.3, from:0.0, to:0.9});
            this.resizeObject(this.blinder, this.wrapper.offsetWidth-2, this.wrapper.offsetHeight-3);
            new Effect.Appear(this.msg.id, {duration:0.3, from:0.0, to:1.0});
            this.resizeObject(this.msg, this.wrapper.offsetWidth-10, this.wrapper.offsetHeight-11);
        } else {
           // do nothing...
           // alert('Already visible...');
        }
    }

    // slips the new content into a temp holder, fades out the old content 100%
    // calls the update function after a moment
    this.finish = function(html) {
        this.temp.innerHTML = html;

		//alert(this.blinder.id);
		//alert(this.msg.id);
        new Effect.Fade(this.blinder.id, {duration:0.3, from:0.9, to:1.0});
        new Effect.Fade(this.msg.id, {duration:0.3, from:1.0, to:0.0});
        var ajaxWait = this;
        setTimeout(function () { ajaxWait.update(); }, 300);
    }

    // fades in the new stuff
    this.update = function() {
		try
		{
			this.target.innerHTML = this.temp.innerHTML;
			this.temp.innerHTML = "";
			new Effect.Fade(this.blinder.id, {duration:0.5, from:1.0, to:0.0});
		}catch(ex)
		{
			//ex = ex;
            log_exceptions(" Method: - update  of requesthandler.js " + ex.message);
		}
    }


    // these can be removed if the functionality exists already in a JS library

    // move an object to the specified top and left position
	this.resizeObject = function (obj, width, height) {

   		// here we have to do some weird stuff because of browser issues
    	if(width != "" || width == 0) {

			if( navigator.appName == "Microsoft Internet Explorer")
				obj.style.width = width;
			else
				obj.style.width = width + "px";
		}


        if(height != "" || height == 0) {
			if( navigator.appName == "Microsoft Internet Explorer")
				obj.style.height = height;
			else
				obj.style.height = height + "px";
		}

	}

}


function RequestHandler()
{
	this.type			 = "";
	this.requestedPageNo = 1;
	this.observers       = new ArrayList();
	this.list_type		 = "all";  // all, news events, user events, people
	this.sorting		 = "popular";
	this.contributor_filter = "popular";
	this.category		 = "all";
	this.clear_cache	 = false;
	this.clear_location  = false;
	this.sub_list_id	 = ""
	this.addVars		 = ""
    this.latestRequestTimeId = Array();
}

RequestHandler.prototype.update = function(widget_name, msg_pos, addition_params){
	try
	{
		/*
			Its creating problem on manage_blog page so i have initialize it again.
		*/
		if(typeof("addition_params") != 'undefined')
		{

		}
		domain = location.protocol + "//" + location.host;
		if(widget_name == "events" || widget_name == 'people')
		{
			setCookie("current_" + widget_name + "_page", this.requestedPageNo);
		}

		//load observer
		anObserver = this.getObserver(widget_name);
		url = domain + "/" + this.type + "/cb_" + widget_name;

		//construct parameters
		var getVars = "requested_page=" + this.requestedPageNo;
		getVars += "&page=" + this.requestedPageNo;
		if(anObserver.my_list_type != null)
		{
			getVars += "&type=" + anObserver.my_list_type;
			this.list_type = anObserver.my_list_type;
		}
		else
		{
			getVars += "&type=" + this.list_type;
		}
		
		getVars += "&category=" + this.category;
		getVars += "&filter=" + this.sorting;
		getVars += "&contributor_filter=" + this.contributor_filter;
		getVars += "&ne=" + readCookie("northeast");
		getVars += "&sw=" + readCookie("southwest");
		getVars += "&clear_cache=" + this.clear_cache;
		getVars += "&clear_location=" + this.clear_location;
		getVars += "&" + this.addVars;

		if (this.sub_list_id != ""){
			getVars += "&" + addition_params;
			var map_reload = false
		}else{
			getVars += "&" + anObserver.addition_params;
			var map_reload = true
		}
		setCookie ("type_category_filter", (this.list_type + "," + this.category + "," + this.sorting + "," + this.contributor_filter) );
		
		this.list_type = 'all';/* change back to its default value as mostly widget list has default value. */
		
		// special case for sublist updates
		if (this.sub_list_id != ""){
			widget_name = widget_name + "_" + this.sub_list_id
		}

        // create a time stamp for an ID and save it in the lastRequest array
        // if the same request is made more than once we check the time ID and ignore the older request and do nothing
        // the stored ID is based on the widget_name so two different widget requests don't mess with each other
        var d = new Date();
        var requestTimeId = d.getTime()/1000;
        this.latestRequestTimeId[widget_name] = requestTimeId;

        // declare wait object
		try
		{
			var ajaxWait = new AjaxWait(widget_name, msg_pos);

			if(!ajaxWait.error) {    // if wait methods built correctly
				ajaxWait.start();       // start the waiting effect...
			}
		}catch(ex){
			//alert(ex.message);
              log_exceptions(" Method: - RequestHandler.prototype.update  block 1 " + ex.message);
		}

        new Ajax.Request(url,
						{
					 		parameters:getVars,
					 		asynchronous:true,
					 		onLoading:function(){

					 		}.bind(this),
					 		onComplete: function(transport){
								try {
									if($(widget_name + '_top')!==null)	{
                                        // if a wait state exists, finish effect
                                        // otherwise just load the new content with no effect...

                                        // only follow through with this request if it hasn't been trumped by a similar but new request
                                        if(requestTimeId == this.latestRequestTimeId[widget_name]) {
                                            if(!ajaxWait.error) {
                                                
                                                ajaxWait.finish(transport.responseText);
                                                //need better way of evaluating javascript than looking for Videos_top
                                                if ($('embedded_javascript') != null && $(widget_name + '_top').id != 'undefined' &&
                                                   $(widget_name + '_top').id == "Videos_top") {
                                                	//eval($('embedded_javascript').innerHTML);
                                                	//initFunc();
                                                	
													var newScript = document.createElement('script');
													newScript.type = "text/javascript";
													newScript.text = "initFunc();";
													document.getElementById("embedded_javascript").appendChild(newScript);
                                                	
                                                }
												/*my_top_pos = $(widget_name + '_top').up(1);
												if(my_top_pos != null)
												{
													my_top_pos.scrollTo();
												}
												else
												{
													$(widget_name + '_top').scrollTo();
												}*/
											} else {
                                               $(widget_name + '_top').update('');
                                               new Insertion.Top($(widget_name + '_top'),transport.responseText);
                                            }
                                        } else {
                                            // do nothing
                                            //alert("Ignored: " + requestTimeId + " vs " + this.latestRequestTimeId[widget_name])
                                        }
                                    }
                                    
                                    if (this.clear_location) {
										reset_region_link();
									}
								}catch(e) {	
									//alert(ex.message);	
									log_exceptions(" Method: - RequestHandler.prototype.update  block 2" + e.message);
								}
								
								try{
									if (widget_name=='new_comments_landing'){
										Element.toggle('comments_lists_event_landing');
									}
								} catch(e){
									//log_exceptions("Not on event landing page");
                                    log_exceptions(" Method: - RequestHandler.prototype.update  block 3" + e.message);
								}
					 		}.bind(this) //end Complete function
						}
						);

		// reset the clear cache function so that we do not clear unecessary lists
		if (this.clear_cache){
			this.clear_cache = false;
		}

		this.sub_list_id = ""

		// reload flash if necessary
		if (map_reload){
			if (anObserver.reload_map) {
				reloadFlash();
			}
		}

	} catch(ex){
	  //alert(ex.message);
	  //log_exceptions("Method:RequestHandler Update " + ex.message);
      log_exceptions(" Method: - RequestHandler.prototype.update  block 4" + ex.message);
	 //alert(ex.message);
	}
}

// set parameters
RequestHandler.prototype.setParameters = function (requestedPageNo, list_type, category, filter, callback_controller) {
	/*
		i'm adding flexiblity in sending requests as some page can have callbacks from diferent controllers
		before its only set in new_application.js
		e.g profile page has callbacks from user,image,video and main
	*/

	if(typeof(callback_controller) != 'undefined')
	{
		this.type = callback_controller;
	}
	
	this.requestedPageNo = requestedPageNo;
	this.list_type		 = list_type;
	
	if (typeof(filter) == 'string')
	{
		this.sorting		 = filter;
		this.contributor_filter = filter;/*if we give "" here then history manager dont work as we are using contributor_filter everywhere at server side.*/
	} else { // assuming it will be an array		
		this.sorting		 = filter[0];
		this.contributor_filter = filter[1];
	}
	
	this.category = category;
}

	// add an observer
RequestHandler.prototype.addObserver = function (widget_name, reload_map,extra_param,my_list_type){
	if(typeof(extra_param) != "undefined")
	{
		observer = new ListObserver(widget_name,extra_param);
	}
	else
	{
		observer = new ListObserver(widget_name);
	}
	
	if(typeof(my_list_type) != "undefined")
	{
		observer.my_list_type = my_list_type;					
		//alert("add observer :: " + observer.my_list_type);
	}
	
	observer.reload_map = reload_map;
	this.observers.add(observer);
	
}

// get the observer
RequestHandler.prototype.getObserver = function (widget_name){
	for (var count = 0; count < this.observers.count(); count++) {
		anObserver = this.observers.getAt(count);
		if (anObserver.widget_name == widget_name) {
			return anObserver;
		}
	}
	return null;
}

// clear cache
RequestHandler.prototype.clearCache = function(){
	this.clear_cache = true;
}

RequestHandler.prototype.retrieve_url = function(tinyMCEInstance, controller_name, cb_name, elem_name, story_url, page_type, page_id,action_type){
	if(page_type=='contributed-news') page_type ='Event'
	var getVars = "page_type=" + page_type;
	getVars += "&page_id=" + page_id;
	getVars += "&story_url=" + escape(story_url);

	url = domain + "/" + controller_name + "/" + cb_name;
	var response1_text="";
	try
	{
		new Ajax.Request(url,
					{
				 		parameters:getVars,
				 		asynchronous:true,
				 		onLoading:function(){
				 			Element.show("div_urls_rss_spinner");
				 		}.bind(this),
				 		onComplete: function(transport){
							var json_data = eval("("+transport.responseText+")");	
				 			var summary_result = "<br /><div id='satisfiedWithSummary'><strong>";
							//if(page_type == "Event")
							//{								
							//}
							Element.hide("div_urls_rss_spinner");
							if(json_data.status == 'cancel')/* this case given url exist in the blacklist_ursl or given url is not responding */
							{
				 				summary_html = '';
								if(page_type == "Event")
								{
									/*"allvoices was not able to pull any article from the URL you gave us.<br/>Want to fill this out anyway?"	*/
									$("error_text").innerHTML = json_data.message;
									$("error_text").show();
								}
								if(action_type == 'story')
								{
									new Insertion.Top('div_urls_rss_form',get_error_list_html(json_data.message.split("#"),error_list.url_get_content,''));
								}
								else
								{
									new Insertion.Top('div_urls_rss_form',get_error_list_html(json_data.message.split("#"),error_list.url_get_content,''));
								}			
								$('getsummary').enable();
								//Element.show('publish');								
							}
							else if(json_data.status == 'ok')/*when we get summary & title of given url successfully*/
							{
																
								Element.show('summary_row');
								Element.show('title_row');
								//Element.show('city_row');
								//Element.show('country_row');
								Element.show('tag_row');
								
								summary_result += error_list.satisfied_with_summary;
								//splitResopnseText = transport.responseText.split('-@delimiter@-');
								summary_html = json_data.summary;
								title_text = json_data.title;								
								//if(page_type == "Event")
								//{
									document.getElementById('story_url').readOnly=true;
								//}

                                Element.show('publish_button');
								Element.hide('getsummary_button');	
								
								summary_result += "</strong></div>";
								
								if($('satisfiedWithSummary')) //removing previous displayed div
								{
									Element.remove('satisfiedWithSummary');
								}
								new Insertion.Top('summary_top', summary_result);
								Element.hide("div_urls_rss_spinner");
								tinyMCEInstance.get(elem_name).setContent(summary_html);
								$('story_title').value = title_text;								
							}														
							/*if (transport.responseText == "1") { // indicates error
				 				//summary_result += error_list.unable_to_retrieve_summary;
				 				summary_html = '';
								if(page_type == "Event")
								{
									$("error_text").innerHTML="allvoices was not able to pull any article from the URL you gave us.<br/>Want to fill this out anyway?"
								}
								Element.show('publish');
				 			} else {
								summary_result += error_list.satisfied_with_summary;
								splitResopnseText = transport.responseText.split('-@delimiter@-');
								summary_html = splitResopnseText[0];
								title_text = splitResopnseText[1];

								//if(page_type == "Event")
								//{
									document.getElementById('story_url').readOnly=true;
								//}
								Element.show('publish');
								Element.hide('getsummary');
							}*/
				 		}.bind(this) //end Complete function
					}
					);
	} catch(ex){
      //log_exceptions("Method:RequestHandler - retrieve url function " + ex.message);
      log_exceptions(" Method: - RequestHandler.prototype.retrieve_url " + ex.message);
	}
	return true;
}


