jQuery.noConflict();

var loaded = false;

document.observe('dom:loaded', function() {
	if (loaded == true) { return false; }
	loaded = true;
	
  var searchResults = $('clipSearchResults');
  var searchResultsPaginationTop = $('searchResultsPaginationTop');
  var searchResultsPaginationBottom = $('searchResultsPaginationBottom');
  if (searchResults && searchResultsPaginationTop && searchResultsPaginationBottom) {
    var results = new SearchResultList(searchResults);
    var paginationTop = new SearchResultListPagination(searchResultsPaginationTop, results, null);
    var paginationBottom = new SearchResultListPagination(searchResultsPaginationBottom, results, paginationTop);
		
		// periodically check
		jQuery(function($) {
			var not_found_text = $("#not_found_text").text();
			$("#clip_results").at_intervals(function() {
				num = results.items().length;
		    if (results.clips_num_prev != num) {
		      results.clips_num_prev = num;
		      results.clips_hide_cnt = 0;
				}
		    else if (results.clips_hide_cnt != -1) {
		      results.clips_hide_cnt += 1;
					//console.log("interval... clips: "+num+" hide_cnt: " + results.clips_hide_cnt)
		      if (results.clips_hide_cnt >= 20) {
						$("#clip_results").hide(); // pause interval
						$("#video_search_loader").hide();
						$("#clip_check").hide();
						if (num == 0)	$(".edit_left_search_info").text(not_found_text);
		        results.clips_hide_cnt = -1;
		      }
				}
		    else if (results.clips_hide_cnt == -1) {
					if (num == 0)	$(".edit_left_search_info").text(not_found_text);
		    }
			}, { 
				name: "pagination",
				delay: 1500
			});
		});

  }
});

var SearchResultList = Class.create({

  initialize: function(list) {
		this.clips_num_prev = 0;
		this.clips_hide_cnt = 0;
    this.list = $(list);
		//
		this.num_engines = 0;	//
		this.setupAsyncPoller();
    this.onNewData = null;
    this.onNewDataTwin = null;
  },

  items: function() {
    return this.list.select('li');
  },

	setupAsyncPoller: function() {
    url = this.list.readAttribute('pollerUrl');
    job_ids = this.list.readAttribute('jobs');
    if (job_ids) {
      job_ids = job_ids.split(';')
    } else {
      job_ids = []
    }
		this.num_engines = job_ids.length;
    job_ids.each(function(job_id) {
			//console.log("setupAsyncPoller job_id: "+job_id)
      new PeriodicalExecuter(function(executer) {
        this.poll(executer, url, job_id);
      }.bind(this), 3.5);
    }, this);
  },

  poll: function(executer, url, job_id) {
    executer.failures = executer.failures || 0;
    new Ajax.Updater(
      this.list,
      url,
      {
        parameters:  { job_id: job_id },
        method:      'get',
        evalScripts: true,
        insertion:   'bottom',
        onSuccess:   function(response) {
          executer.stop();
					if (this.num_engines <= 0) {
						jQuery("#video_search_loader").hide();
					} else if (response.responseText != '' && this.onNewData) {
						//console.log("onSuccess NewData - num_engines: "+this.num_engines+" status: "+response.status+" job_id: "+job_id)
						this.onNewData.defer();
					}	
					this.num_engines--;
        }.bind(this),
        onFailure: 	 function(response) {
          if ((executer.failures++) >= 5) {
            executer.stop();
						//console.log("onFailure STOPPED - failures: "+executer.failures+" status: "+response.status+" job_id: "+job_id+" num_engines: "+this.num_engines)
          }
        }
				// TODO !?
				// // status 200, 201, 204
				//onSuccess: function(response) {
				// 	this.num_engines--;
				// 	//console.log("onSuccess - num_engines: "+this.num_engines+ " response: "+response.status)
				//           executer.stop();
				// 	if (this.num_engines <= 0) {
				// 		jQuery("#video_search_loader").hide();
				// 	} else if (response.status == 201) {
				// 		console.log("onSuccess - NewData num_engines: "+this.num_engines+ " response: "+response.status)
				// 	          if (this.onNewData) this.onNewData.defer();
				// 	}
				//         }.bind(this),
				//         // status 304, 404
				//onFailure: function(response) {
				// 	console.log("onFailure - failures: "+executer.failures+" response: "+response.status)
				//           if ((executer.failures++) >= 5) {
				//             executer.stop();
				//           }
				//         }
      }
    );
  },

  showWindow: function(start, length) {
    this.items().each(function(item) {
      item.hide();
    });
    this.items().slice(start, parseInt(start) + parseInt(length)).each(function(item) {
      item.show();
			if (item.id) {
				var do_tooltip = true;
				jQuery.each(jQuery.browser, function(i, val) {
					if (i=="msie" && (jQuery.browser.version.substr(0,3) == "6.0" || jQuery.browser.version.substr(0,3) == "7.0")) {
						do_tooltip = false;
					}
				});
				if (do_tooltip) {
					jQuery(".clip_added_"+item.id).tooltip_search({
						bordercolor: '#00112d',
						bgcolor: '#F8F8F8',
						fontcolor: '#666666',
						fontsize: '14px',
						filetype: 'html'
						})
					jQuery("li#"+item.id).removeAttr("id");
				}	
			}
    });
  }
});

var SearchResultListPagination = Class.create({
  
	initialize: function(container, resultList, twin) {
    this.container  = $(container);
    this.resultList = resultList;
    this.currentPage = 1;
    this.perPage = jQuery('#searchResultsPerPage').html();
		this.twin = twin;
		this.setupScrolling();
		if (twin != null) {
			this.resultList.onNewData = this.setupScrolling.bind(this);
		  this.twin.setTwin(this);
		}
	},

  setTwin: function(twin) {
		this.twin = twin;
		this.resultList.onNewDataTwin = this.setupScrolling.bind(this);
	},

	setupScrolling: function() {
		if (this.twin != null) {  // show results only once
			this.showResults(this.currentPage-1);
			this.twin.printPagination();
		}	
    this.printPagination();
  },

  showResults: function(index) {
    this.resultList.showWindow(index * this.perPage, this.perPage);
  },

  // callback function for jQuery pagination
	paginationClick: function(new_page_index, pagination_container) {
		this.currentPage = new_page_index+1;
		if (this.twin) {
		 	this.twin.currentPage = this.currentPage;
		}	
		this.setupScrolling();
    return false;
	},
		
  printPagination: function() {
    this.container.update('');

		var num = this.resultList.items().length;
		var current = this.currentPage;
		var items_per_page = this.perPage;
		var fn = this; // Clipflakes: pagination calls paginationClick!
		var id = this.container.readAttribute('id');
		jQuery(function($) {
			$('#edit_left_clips_num_index').text(num);
			$('#'+id+'').pagination(num, { 
				current_page: current-1,
				items_per_page: items_per_page,
				num_edge_entries: 2,
				prev_text: "&laquo;",
				next_text: "&raquo;",
				prev_show_always: false,
				next_show_always: false,
				callback: fn
		  });
		});
  }

});

jQuery(function($) {
	var allowed_generic = parseInt($('#countdown').text());
	function key_updown(text_id, countdown_id, allowed_in) {
		var allowed = allowed_generic;
		if (allowed_in) allowed = allowed_in;
	  var countdown = $('#'+countdown_id);
	  var text = $("#"+text_id).val();
	  var length = text.length;
    var rest = allowed-length;
	  countdown.html(function() {
			var color;
			if (rest < 0) color = 'red';
		  return "<span style='color:"+color+";'>"+rest+"</span>";
		});
	  // TwitterX, CommentX TODO length=0 or >140 disable submit button
	  //console.log("allowed: "+allowed+" allowd_in: "+allowed_in+" length: "+length+" text: "+text)
	}
	$('#text').keypress(function() {
		key_updown('text', 'countdown');
  });
	$('#text').keyup(function() {
		key_updown('text', 'countdown');
  });

	$('#program_description').keypress(function() {
		key_updown('program_description', 'countdown', 500);
	});
	$('#program_description').keyup(function() {
		key_updown('program_description', 'countdown', 500);
	});
	
	$('#program_tags').keypress(function() {
		key_updown('program_tags', 'countdown_tags', 120);
	});
	$('#program_tags').keyup(function() {
		key_updown('program_tags', 'countdown_tags', 120);
	});

	$('#login_password_field').keyup(function(event) {
		if (event.keyCode == Event.KEY_RETURN && !event.altKey && !event.shiftKey) {
			document.getElementById('login_form').submit();
		  Event.stop(event);
	  }
	});

	// tipsy
	$("*[class^=tipsy_navigation_]").tipsy({title: 'cdata', fade: false, gravity: 's', html: true});
	$("*[class^=tipsy_clipshow_]").tipsy({title: 'cdata', fade: false, gravity: 'e'});
	$("*[class^=tipsy_user_]").tipsy({title: 'cdata', fade: false, gravity: 'w'});
	$("*[class^=tipsy_category_]").tipsy({title: 'cdata', fade: false, gravity: 'w'});
	$("*[class^=tipsy_playall_]").tipsy({title: 'cdata', fade: false, gravity: 's'});
	$("*[class^=tipsy_edit_]").tipsy({title: 'cdata', fade: false, gravity: 's'});
	$("*[id^=tipsy_query_]").tipsy({title: 'cdata', fade: false, gravity: 's'});
	$("*[class^=tipsy_recommend]").tipsy({title: 'cdata', fade: false, gravity: 's'});
	
	// slider scrollable
	$("#chained").scrollable({circular: true, mousewheel: true}).navigator().autoscroll({
		interval: 10000
	});	

	$("#embed_chained").scrollable({circular: true, mousewheel: true}).navigator().autoscroll({
		interval: 6000
	});	
	
});


