(function($){
   $.fn.extend(
   {	
      resizeImg: function(width, height, not_stretch, bg_color)
      {
         not_stretch = (not_stretch == undefined) ? false : not_stretch;		

         if(not_stretch)
            bg_color = (bg_color == undefined) ? '#000' : bg_color;

//         this.each(function()
//         {	
            $(this).load(function()
            {

               $(this).parent("a").css({'height':height+'px', 'width':width +'px', 'overflow':'hidden', 'text-align':'center', 'display' : 'block'});			
               var shorter_side = 'w';			

               if($(this).width() > $(this).height())
                  shorter_side = 'h';
                			
               if(shorter_side == 'w')
               {					
                  if(!not_stretch)
                     $(this).width(width);

                  var negative_bias_top = (height - $(this).height()) / 2;				
                  $(this).css({'margin-top' : negative_bias_top + 'px'});			
               }
               else
               {
                  if(!not_stretch)
                  {
                     $(this).height(height);
                     var bias_top = (height - $(this).height()) / 2;				
                     $(this).css({'margin-top': bias_top+'px'});
                  }				

                  var negative_bias_left = (width - $(this).width()) / 2;				
                  $(this).css({'margin-left': negative_bias_left + 'px'});			
               }

               if(not_stretch)
                  $(this).parent("div").css('background', bg_color); 
            });
//         });
         return this;	
      }
   });

   $.extend(
   {
      delPX: function(val)
      {
         return parseInt($.trim(val.replace('px', '')));
      },

      isChrome: function()
      {
         var is_chrome = false, chrome_version = false;

         if (navigator.userAgent.toLowerCase().indexOf('chrome') > -1)
         {
            is_chrome = true;
            chrome_version = navigator.userAgent.replace(/^.*Chrome\/([\d\.]+).*$/i, '$1');
         }
         return is_chrome;
      }
   
   });

})(jQuery);

var search_str_focus = false;
var save_href;

function clickWord(word, noautoquotes){    
   var form    = $(".query-form");
   var request = $(".query-form input[name='request']");
   var page    = form.find("input[name='page']");
   var input_request = request.val();
   var new_req = '';
   var reg1 = /"/;
   var reg2 = /\s+/;
   var reg3=/\s+$/;

   if (word != '')
   {
      if(reg2.exec(word) && !reg1.test(word) && !noautoquotes)
         word = '"' + word + '"';

      var reg = new RegExp(word, 'gmi');

      if(reg3.exec(input_request))
      {
         input_request = input_request.replace(word + ' ', '');
         input_request = input_request.replace(/\s+$/,'');
      }

      if(!reg.exec(input_request))
      {
         if(input_request != '')
            new_req = input_request + ' ' + word;                          
         else
            new_req = word;
      }
      else
      {  
         new_req = input_request.replace(word, '');
         new_req = new_req.replace(/\s{2,}/,' ');
         new_req = new_req.replace(/\s+$/,'');
	   }
	}else{	newReq = '';	}
	request.val(newReq);	
	page.val(1);
	form.submit();
}

function clickSubmit(){
	var form = 	$(".query-form");
	var page = 	form.find("input[name='page']");
	
	page.val(1);
	form.submit();
}

function clickHome(){
	var form = 	$(".query-form");
	var page = 	form.find("input[name='page']");
	var request = 	$(".query-form input[name='request']");	

	request.val('');
	page.val(1);
	form.submit();
}
function addWordInSF(word){
	var request = 	$(".query-form input[name='request']");	

	var inputRequest = request.val();	
	var reg = /"/;
	var reg2 = /\s+/;
	if(reg2.exec(word) && !reg.exec(word)){word='"'+word+'"';} 
	var reg = new RegExp(word, 'gmi');
	if(inputRequest !=''){
		if(!reg.exec(inputRequest)){
			newReq = inputRequest.replace(/\s+$/,'');
			newReq = newReq+' '+word+' ';
		}else{newReq = inputRequest;}
	}else{
	newReq = word+' ';
	} 
//	newReq = newReq.replace(/\s+/,' ');
	request.val(newReq);
}

function delWordInSF(word){
	var request = $(".query-form input[name='request']");	
	var inputRequest = request.val();	
	var reg = new RegExp(word, 'gmi');
//	var reg2 = /\S+\s+\S+/;
	var reg2 = /\s+\S+/;
	var reg2a = /\s+\"/;
	if(reg2.exec(word)){
		var reg3 = new RegExp('"'+word+'" ', 'gmi');
		if(reg2a.exec(inputRequest)){word = ' "'+word+'" ';}
		else{word = '"'+word+'" ';}
	}else{
		var reg3 = new RegExp(word+' $', 'gmi');
		if(reg2.exec(inputRequest)){word =' '+word+' ';}
		else{word =word+' ';}
	}
	if (word != ''){
		if(reg.exec(inputRequest) && reg3.exec(inputRequest)){
               		request.val(inputRequest.replace(word, ''));
		}
 	}
}
function setTab(id){
	var form = 	$(".query-form");
	var tab = 	form.find("input[name='tab']");
	var page = 	form.find("input[name='page']");
	page.val(1);
	tab.val(id);
	form.submit();
}

function setPage(num){
	var form = 	$(".query-form"); 
	var page = 	form.find("input[name='page']");
	page.val(num);
	form.submit();
}
 
function saveCoordWord(word,x,y,size){
	if(word != ''){	var wa = "{\""+word+"\", "+x+","+y+","+size+"}";}
	$('.query-form input[name="wa"]').val(wa);
}

function sendViaGo(){
	var url = $(this).attr('href');
        type = ($('.hint').html() == null) ? 'servise' : 'himsh';
        save_href = url;
        url = encodeURIComponent(url);
	if (url.search('/go/?') == -1) {
		var topic_id = $('#topic-id').val();
		var partner_id = $('#partner-id').val();
		var request = $(".input-request").val();
		var page = $(".query-form input:hidden[name='page']").val();
		$(this).attr('href', '/go/?partnerid='+partner_id+'&topicid=' + topic_id + '&request='+request+'&embed_url=&type=' + type + '&url='+url+'&num='+page)
	}
}
function resetHref(){
   $(this).attr('href', save_href);
}

$(function(){
	var form = $(".query-form"); 
	var pageEl = form.find("input[name='page']");

        var topic_id   = $('#topic-id').val();
        var partner_id = $('#partner-id').val();
        var sv         = $('#sv').val();
        var icons_count = $('#icons-count').val();
        var ban_request_type = $('#ban-request-type').val();
        var count_page = $('#count-page').val()
	
	$(".search-map a").bind('click', function(){
		var text = $(this).attr('title');
		if(text == ''){text = $(this).text();}
		var parentDiv = $(this).parent('div');
		var left = $.delPX(parentDiv.css('left'));
		var top  = $.delPX(parentDiv.css('top'));
		var fsize= $.delPX(parentDiv.css('font-size'));
		saveCoordWord(text, left, top, fsize);
		clickWord(text);
                return false;
	});
 
	$(".search-map a").mouseover(function(){
		var text = $(this).attr('title');
		if(text == ''){text = $(this).text();}
		addWordInSF(text);
	});

	$(".search-map a").mouseout(function(){
		var text = $(this).attr('title');
		if(text == ''){text = $(this).text();}
	   	delWordInSF(text);
	});

	$(".tabs a").click(function()
        {
           setTab($(this).parent('div').index());
           return false;
        });

	$(".additional a").click(function(){
		var reg = /\d+/i;
		var page = $(this).text();
		if(reg.test(page)){setPage(page);}
	});
 
        if(parseInt(pageEl.val()) > 1) $(".prev").css({'color':'#5892D8'});
	else $(".prev").css({'cursor':'default'});

        if(parseInt(pageEl.val()) < count_page) $(".next").css({'color':'#5892D8'});
	else $(".next").css({'cursor':'default'});

	$(".additional .prev").click(function(){
		var page = parseInt(pageEl.val());
		if(page > 1) setPage(page - 1);
	});

	$(".additional .next").click(function(){
		var page = parseInt(pageEl.val());
		if(page < count_page) setPage(page + 1);
	});

	$('body').keydown(function(event){
  		if (window.event) event = window.event;
		if(event.keyCode == 13 && search_str_focus){
			pageEl.val(1);
			form.submit();
		}
	});
	
	$(".input-request").focus(function(){search_str_focus = true});
	$(".input-request").blur(function(){search_str_focus = false;});

        $('.search-results li a').mousedown(sendViaGo);
//        $('.search-results li a').mouseup(resetHref);
//        $('.search-results li a').each(sendViaGo);

	$('.quintura-logo').click(function(){
          $('.input-request').val('');
	  $('.query-form').submit();
          return false;
	});

        $('.images li img').fullSizeImg();

/* 
   if($('.search-results').html() != null)
      Hints.create(topic_id, partner_id, sv);
*/

   Ads.create(topic_id, partner_id, ban_request_type, icons_count);
   Complete.create(topic_id);
});  
