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;
function search_poll_releavance()
{
	id = "poll_question"
	if(is_empty(id)){
		//$(id).focus();
	}else{
		var question_text = document.getElementById(id).value;
		var actionUrl='/poll_creation/search_releavce_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)
{ 
	//debugger;
	//window.opener.
    show_rejection_result(poll_id, total_polls);
    setTimeout("group_hideTooltip();",1000);
    //setTimeout("window.close();",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)
{
   //debugger;
   is_poll_exist = false;
   index = 0;
   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);
	           
	        //document.location.href = "/poll_creation/greeting_page/?page_no=2"
	     }else if(number_of_polls_attempted == total_polls){
		 		$("unans_polls_msg").hide();
				setTimeout("display_swarm_modal('/poll_creation/solicit_create_poll_completed')",2000);
	            
	        //document.location.href = "/poll_creation/solicit_create_poll_completed"           
	     }
    }
 return !is_poll_exist	
}

function getContentByAjax(url, updater_div, loader)
{  
	var process_result = new Ajax.Updater(updater_div, url, {asynchronous:true, evalScripts:true, onLoading:function(request){loader.style.zIndex=5;}, onSuccess:function(request){loader.style.zIndex=-5;}});
	return false;
}

function getContentByAjaxRJS(url, this_obj)
{  
	var message_div = $('message');
	if( message_div != null )
	{
		message_div.hide();
	}
	url = url + "?val="+$(this_obj).value
	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 = 'T';
}

function home_toprated()
{
	$('n_poll').hide();
	$('f_poll').hide();
	$('t_poll').show();
	$('toprated_btn').addClassName('currentSection');
	Element.removeClassName('newest_btn', 'currentSection');
	Element.removeClassName('related_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();
	}
	else if(next_tab == 'T')
	{
		home_toprated();
	}
}

function save_google_image( image_url ){

	encodedImageUrl = encodeURIComponent(image_url)
	remoteUrl = '/medias?url='+ encodedImageUrl 
	var processed_result = new Ajax.Updater('uploaded_media', remoteUrl, {asynchronous:true, evalScripts:true, onLoading:function(request){ $('loading_image').style.zIndex = 5;$('loading_image').style.display="block" }, onSuccess:function(response){var server_resText= response.responseText || "no response from server";
		modify_div(server_resText);
		$('loading_image').style.zIndex = -5;
		$('loading_image').style.display="none"
	}});	
	//var processed_result = new Ajax.Updater('uploaded_media', remoteUrl, {asynchronous:true, evalScripts:true, onComplete:function(response) {show_tooltip_window( ajax_url, input_obj, question_type, search_texId, 2 );}});
}	

function OnLoad( poll_question ) {
  this.current_page = 0;
  this.all_results = 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);
  search_text = poll_question;
  this.siteSearch.execute(poll_question);	  
  document.getElementById('search_text_box').value = poll_question
}

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) {
			page_index[cursor.currentPageIndex] = cursor
			result[cursor.currentPageIndex] = this.siteSearch.results;
			
			this.all_results[cursor.currentPageIndex] =  this.siteSearch.results;
			this.siteSearch.gotoPage(cursor.currentPageIndex + 1 );
			current_result = result[cursor.currentPageIndex]

			if(navigator.userAgent.indexOf("Opera") != -1){
				cursor.currentPageIndex = cursor.pages.length - (cursor.currentPageIndex + 1)				
				this.siteSearch.results = result[cursor.currentPageIndex]
			}	
			set_result(cursor.currentPageIndex, cursor.pages.length, this.siteSearch.results)	
		}
	}
	
	 displayResult(); 
}


function set_result(currentPageIndex, pages, current_result ){
	
	more_result = new Array();
	if(currentPageIndex > 0 ){
	var previous_result = this.all_results[currentPageIndex - 1 ]
	for(i=0; i<currentPageIndex-1 ; i++){
		if(currentPageIndex!=1){
			previous_result[i] = current_result[i]          
		}
	}
	previous_result[8] = current_result[currentPageIndex - 1 ] 
	this.all_results[currentPageIndex - 1] = previous_result ;
	
	if( pages - 1 == currentPageIndex ){
		last_result = this.all_results[currentPageIndex]
		j = 0;
		for( i=currentPageIndex; i<last_result.length; i++){
			more_result[j] = last_result[i]	
      		j = j + 1
		}
      	this.all_results[currentPageIndex] = more_result;
	} 
} 
	
}


function displayResult(){
  
 	if(this.all_results.length > 0){
		  $('google_search').style.display ="block"
		  $('paginate').style.display ="block" 
		   var search_result = "<div id='0' class='resultsListContainer'><ul id='resultsList'>" ;
		  current_result = this.all_results[0];
		  
		   for(var i=0; i<current_result.length ; i++ ){
			search_result  = search_result +  "<li><a id='first_page' href='javascript:save_google_image(\"" +current_result[i].url+ "\")'>"   + "<img src='"+current_result[i].tbUrl+"'"+" width='100px' title='Click to select image' /></a></li>";
  			}
			
		  search_result = search_result + "</div></ul><div class='clear16'></div>"
		  document.getElementById("google_search").innerHTML = search_result	
			if(navigator.userAgent.indexOf("Opera") != -1){	
				var pagination = "<br/><br/><br/><div>" ;
		    }else{
				var pagination = "<div>" ;
			}
			
			for(var i=0; i<this.all_results.length; 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;" ;
					}
			 }
			
		    document.getElementById("paginate").innerHTML = pagination + "</div>";
		 	$('page0').style.textDecoration = "none" 
 	}else{
		
		document.getElementById("google_search").innerHTML = "<div id='0'> No result found </div>"
		$('paginate').style.display ="none" 
	}
 }   

function paginatedResult(page_index){
 
  for(i=0; i<this.all_results.length ; i++){
		$('page'+i).style.textDecoration = "underline";
  		$('page'+i).style.color = "#3181c0";
   }
  $(('page'+page_index)).style.textDecoration = "none";
  $(('page'+page_index)).style.color = "red";
  
  var search_result = "<div id='"+page_index+"' class='resultsListContainer'><ul id='resultsList'>" ;
  current_result = all_results[page_index]  
  
  for(var i=0; i<current_result.length ; i++ ){
	search_result  = search_result +  "<li><a id='first_page' href='javascript:save_google_image(\"" +current_result[i].url+ "\")'>"   + "<img src='"+current_result[i].tbUrl+"'"+" width='100px' title='Click to select image' /></a></li>";
  }
	
	previous_div = document.getElementById(this.current_page);           
    document.getElementById("google_search").removeChild( previous_div );
    document.getElementById("google_search").innerHTML = search_result + "</div></ul><div class='clear16'></div>"
    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/show_more_result?text="+search_text ;*/
	//window.open(remoteUrl, "width=700px, height=400px, scrollbars=yes" );
}

function change_camera_icon(){
  if(question_type == 1){
		question_type = "question";
		Element.removeClassName(question_type ,'camera_btn_bot');
  		$(question_type).addClassName('camera_btn_bot_green');	
  }else{
		Element.removeClassName(question_type,'camera_btn');
  		$(question_type).addClassName('camera_btn_green');	
  }
  		$(question_type).title = 'Image Added';
		popup_window = false;
		group_hideTooltip();	
}

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')){
				OnLoad($('search_text_box').value)	
				$('google_error_msg').innerHTML =""
			}else{
				$('google_error_msg').innerHTML = "Please enter search text."				
			}
			
	  }
	  return  false;
}

function modify_div(server_resText){
	
	if(server_resText.indexOf("mess_errors_image") < 0){
		document.getElementById("close_popup").innerHTML = '<a href="javascript:void(0)" onclick="change_camera_icon()"></a>'		  
	}
	  //$('loading_image').style.zIndex = -5
	//$('loading_image').style.display = "none"
}

function reset_camera(){
	document.getElementById("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_uploaded_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	

}


/*This function is used to delete deal by ajax call*/
function delete_deal(deal_id)
{
	var actionUrl = '/supplier_deal/delete_deal/' + deal_id;
	var divId = 'deal_'+deal_id
	var process_result = new Ajax.Updater(deal_id, actionUrl, {asynchronous:true, evalScripts:true, onSuccess:function(request){new Effect.Fade(divId)}}); 
	return false;
}

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


