var number_of_polls_attempted = 0; //for recording the attempted polls at browser side
var last_poll_ids = new Array(); 
var answer = new Array();
var page_index = new Array();
var result = new Array();
var popup_window =  false;
var is_search_img =  false;
var current_image_type = "";
var image_processed = true;
var times_called =0;
var search_result;
var page_size=12;
var all_results_unpaged = new Array();

function search_poll_releavance()
{
  id = "poll_question"
  if(is_empty(id)){
    //$(id).focus();
  }else{
    var question_text = $(id).value;
    var actionUrl = '/poll_creation/search_relevant_polls/?question_text=' + encodeURIComponent(question_text);
    var process_result = new Ajax.Updater('releavance_polls', actionUrl, {asynchronous:true, evalScripts:true});
  }
}

function returnmedia(imagepath)
{
  stringArray = imagepath.split("#");
  $(stringArray[1]+"_img").src = stringArray[0];
  $(stringArray[1]).style.display = "block";
}

function poll_rejection(poll_id, total_polls) {
  show_rejection_result(poll_id, total_polls);
  setTimeout("group_hideTooltip();",1000);
}

function show_rejection_result(poll_id, total_polls) {
  update_participated_value(total_polls, poll_id);
  var actionUrl = '/poll_result/cant_respond_result/' + poll_id;
  var process_result = new Ajax.Updater(('poll_stat_' + poll_id), actionUrl, {asynchronous:true, evalScripts:true});
}

function update_participated_value(total_polls, poll_id) {
	is_poll_exist = false;
  index = 0;
  if($('poll_facts_div'))
		update_poll_facts(poll_id);
  else if($('log_out_resp_message'))
    getContentByAjax('/show_poll/logged_out_resp_message_by_ajax', 'log_out_resp_message');
   
  for( index = 0; index < last_poll_ids.length ; index++ ){
		if(parseInt(last_poll_ids[index]) == parseInt(poll_id)){
    	is_poll_exist = true;
    }
  }   
  
	if((total_polls > 0)  && (!is_poll_exist) ){
  	last_poll_ids[last_poll_ids.length] = poll_id;
    number_of_polls_attempted = number_of_polls_attempted + 1
    unanswered_polls = total_polls - number_of_polls_attempted
    $('unans_poll_count').update(unanswered_polls);
    
    if(number_of_polls_attempted == 3 && number_of_polls_attempted < total_polls){
    	setTimeout("display_swarm_modal('/poll_creation/greeting_page/?page_no=2&uns_polls="+unanswered_polls+"')",2000);
    }else if(number_of_polls_attempted == total_polls){
    	$("unans_polls_msg").hide();
      setTimeout("display_swarm_modal('/poll_creation/solicit_create_poll_completed')",2000);
    }
  }
 	return !is_poll_exist  
}

function getContentByAjax(url, updater_div)
{  
  var process_result = new Ajax.Updater(updater_div, url, {asynchronous:true, evalScripts:true});
  return false;
}

function getContentByAjaxRJS(url)
{  
  var message_div = $('message');
  if( message_div != null )
  {
    message_div.hide();
  }
  var process_result = new Ajax.Request(url, {asynchronous:true, evalScripts:true});
  return false;
}

function addthis_click(addthis_pub, addthis_url, addthis_title)
{
   var aturl  = 'http://www.addthis.com/bookmark.php';
   aturl += '?v=10';
   aturl += '&pub='+encodeURIComponent(addthis_pub);
   aturl += '&url='+encodeURIComponent(addthis_url);
   aturl += '&title='+encodeURIComponent(addthis_title);
   
   window.open(aturl,'addthis','scrollbars=yes,menubar=no,width=620,height=520,resizable=yes,toolbar=no,location=no,status=no,screenX=200,screenY=100,left=200,top=100');
   return false;
}


function home_related()
{
  $('n_poll').hide();
  $('t_poll').hide();
  $('f_poll').show();
  $('related_btn').addClassName('currentSection');
  Element.removeClassName('newest_btn', 'currentSection');
  Element.removeClassName('toprated_btn', 'currentSection')
  next_tab = 'N';
}

function home_newest()
{
  $('f_poll').hide();
  $('t_poll').hide();
  $('n_poll').show();
  $('newest_btn').addClassName('currentSection');
  Element.removeClassName('related_btn', 'currentSection');
  Element.removeClassName('toprated_btn', 'currentSection');
  next_tab = 'R';
}

var next_tab = 'N';
function rotate_home_page_subtab()
{
  if(next_tab == 'R')
  {
    home_related();
  }
  else if(next_tab == 'N')
  {
    home_newest();
  }
  
}

function save_google_image( preview_url,image_url ){
  if(image_processed){
    encodedImageUrl = encodeURIComponent(image_url)
    remoteUrl = '/medias?imgfor='+$("image_for").innerHTML.strip() + '&url='+ encodedImageUrl 
    var processed_result = new Ajax.Request(remoteUrl, {asynchronous:true, 
                                                        evalScripts:true, 
                                                        onLoading: function(request){ 
                                                                modify_div_before_load() }, 
                                                        onSuccess: function(response){
                                                                var server_resText= response.responseText || "no response from server";
                                                                modify_div(server_resText);

                                                        }});
  }
} 

function search( poll_question ) {
  this.current_page = 0;
  all_results_unpaged = new Array();
  this.siteSearch = new GimageSearch();
  this.siteSearch.setResultSetSize(GSearch.LARGE_RESULTSET);
  this.siteSearch.setRestriction(GimageSearch.RESTRICT_IMAGESIZE, GimageSearch.IMAGESIZE_MEDIUM );
  this.siteSearch.setSearchCompleteCallback(this, onSearchComplete);
  //this.siteSearch.setOnLoadCallback(onSearchComplete);
  search_text = replace(poll_question,"\n"," ")
  this.siteSearch.execute(search_text);   
  $('search_text_box').value = search_text
}

function MyKeepHandler(result) {
  
  save_google_image( result.unescapedUrl, result.tbUrl ); 
}

function onSearchStarting(sc, searcher, query_text)
{
  search_text = query_text;
}


onSearchComplete = function() {
  if (this.siteSearch.results && this.siteSearch.results.length > 0) {
    var cursor = this.siteSearch.cursor;
    if (cursor && cursor.currentPageIndex < this.siteSearch.cursor.pages.length) {
      push_results(this.siteSearch.results)
      if (cursor && cursor.currentPageIndex + 1 < this.siteSearch.cursor.pages.length) {
        this.siteSearch.gotoPage(cursor.currentPageIndex + 1); //this will leave us back in this callback
      }else {
        displayResult();
      }
    }
  }
}

function push_results( results ){
  for (i=0; i < results.length; i++) {
    all_results_unpaged.push(results[i]);
  }
}

function num_of_pages() {
  pages = all_results_unpaged.length / page_size;
  if (pages < 5) return pages
  else return 4;
}

function uiLi(page_index) {
  var search_result = "<div id='0' class='resultsListContainer'>" ;
  current_result = all_results_unpaged
  start_index = page_index*page_size;
  end_index = start_index+page_size
  if (end_index > all_results_unpaged.length) {
    end_index = all_results_unpaged.length
  }
  for(var i=start_index; i < end_index ; i++ ){
    if (i % 4 == 0) {
      search_result = search_result + "<ul id=\"resultsList\">";
    }
    search_result  = search_result +
                     "<li>" +
                     "<a href='javascript:save_google_image(\""+current_result[i].tbUrl+"\", \"" +current_result[i].url+ "\")'>" +
                     "<img src='"+current_result[i].tbUrl+"'"+" width='100px' title='Click to select image' />" +
                     "</a>" +
                     "</li>";
  
    if (i % 4 == 3) {
      search_result = search_result + "</ul>";
    }
  }
  search_result = search_result + "</ul></div><div class='clear16'></div>"
  $("google_search").innerHTML = search_result
}
function displayResult(){
  if(this.all_results_unpaged.length > 0){
      $('google_search').style.display ="block"
      $('paginate').style.display ="block" 
       uiLi(0);
      if(navigator.userAgent.indexOf("Opera") != -1){ 
        var pagination = "<br/><br/><br/><div>" ;
        }else{
        var pagination = "<div>" ;
      }

      for(var i=0; i<all_results_unpaged.length / page_size; i++){
           j = i + 1 ;
          if(i==0){
                     pagination  = pagination +"<a id='page"+i+"'  style='color:red;' href='javascript:paginatedResult("+i+")' >" + j + "</a>&nbsp;&nbsp;" ;        
          }else {
            pagination  = pagination +"<a id='page"+i+"'  href='javascript:paginatedResult("+i+")' >" + j + "</a>&nbsp;&nbsp;" ;
          }
       }

        $("paginate").innerHTML = pagination + "</div>";
      $('page0').style.textDecoration = "none"
  }else{

    $("google_search").innerHTML = "<div id='0'> No result found </div>"
    $('paginate').style.display ="none"
  }
 }

function paginatedResult(page_index){
 
  for(i=0; i < num_of_pages() ; i++){
    $('page'+i).style.textDecoration = "underline";
/*      $('page'+i).style.color = "#3181c0";*/
  }
  $(('page'+page_index)).style.textDecoration = "none";
  $(('page'+page_index)).style.color = "red";
  
  
  uiLi(page_index);
  this.current_page = page_index;
}

function clear_searched_result() {
  $('search_text_box').value =""
  $('google_search').style.display ="none"
  $('paginate').style.display ="none" 
}  

function show_more_result( more_results_url )
{
  window.open ("/show_poll/show_more_result?text="+search_text,"mywindow");
  /*remoteUrl = "/show_poll/stylehow_more_result?text="+search_text ;*/
  //window.open(remoteUrl, "width=700px, height=400px, scrollbars=yes" );
}

function search_image(e){
  
  var keynum;
  if(window.event) // IE
    {
    keynum = e.keyCode;
    }
  else if(e.which) // Netscape/Firefox/Opera
   {
    keynum = e.which;
    }
    if(keynum==13){
        if(!is_empty('search_text_box')){
        search($('search_text_box').value)  
        $('google_msg').innerHTML =""
      }else{
        $('google_msg').innerHTML = "Please enter search text."
      }
      
    }
    return  false;
}

function modify_div(server_resText){
  if(server_resText.indexOf("mess_errors_image") < 0)
    $("close_popup").innerHTML = '<a href="javascript:void(0)" onclick="group_hideTooltip()"></a>'
  else
    $("close_popup").innerHTML = '<a href="javascript:void(0)" onclick="group_hideTooltip()"></a>'
  
  $("create_poll_button").innerHTML = '<a href="javascript:submit_create_poll();"></a>'
  image_processed = true;
}

function modify_div_before_load(){
  $("close_popup").innerHTML        = '<a href="javascript:void(0)"></a>'
  $("create_poll_button").innerHTML = '<a href="javascript:void(0)"></a>'
  $A(['messageExplanation', 'errorExplanation']).each(function(klass){ $('google_msg').removeClassName(klass)})
  $('google_msg').addClassName('loadingExplanation')
  $('google_msg').update("Retrieving image...").show()
  image_processed = false;
}

function reset_camera(){
  $("close_popup").innerHTML = '<a href="javascript:void(0)" onclick="group_hideTooltip()"></a>'
  
  if(question_type == 1){
    question_type = "question";
    Element.removeClassName(question_type ,'camera_btn_bot_green');
      $(question_type).addClassName('camera_btn_bot');  
  }else{
    Element.removeClassName(question_type,'camera_btn_green');
      $(question_type).addClassName('camera_btn');  
  }
      $(question_type).title = 'Click here to add an image';
    $('media_ ed_data').clear();
    $('media_message').hide();
}

function set_google_search_img(){
  is_search_img = true ;  
}

 function reset_google_search_img(){
  is_search_img = false;
}

function is_search_google_img(){
  return  !is_search_img  
}

function showWaiting(){
  ['errorExplanation', 'messageExplanation'].each(function(klass){$('upload_msg').removeClassName(klass)})
  $('upload_msg').addClassName('loadingExplanation')
  $('upload_msg').update('Uploading, please wait...').show()
}

function update_poll_facts(poll_id){
   var poll_facts_div = $('poll_facts_div');
   var Url = '/share_poll/show_poll_facts/'+ poll_id;
   var process_result =  new Ajax.Updater(poll_facts_div, Url, {asynchronous:true, evalScripts:true});
   
}

function getContentByAjaxBrowse(url, updater_div, loader_div)
{  
  var locimg = $('img');
  var process_result = new Ajax.Updater(updater_div, url, {asynchronous:true, evalScripts:true, onLoading:function(request){loader_div.style.display="block";loader_div.style.zIndex=5;locimg.style.zIndex=5;}, onSuccess:function(request){loader_div.style.display="none";loader_div.style.zIndex=-5;locimg.style.zIndex=-5;}});
  return false;
}

function reset_value()
{
  $(current_image_type+"_image").value ="" 
}