var hintcontainer = null;  
 function showhint(obj, txt) {  
    if (hintcontainer==null) {  
       hintcontainer = document.createElement("div");  
       hintcontainer.className="hintstyle";  
       document.body.appendChild(hintcontainer);  
    }  
    obj.onmouseout = hidehint;  
    obj.onmousemove=movehint;
    hintcontainer.innerHTML='<img src='+txt+'>';  
 }  
 function movehint(e) {
     if (!e) e = event; //line for IE compatibility

	var scrollLeft = window.pageXOffset || document.documentElement.scrollLeft || 0;
	var scrollTop = window.pageYOffset || document.documentElement.scrollTop || 0;

	var x = e.clientX+20 + scrollLeft
	var y = e.clientY+20 + scrollTop

	if(e.clientX+hintcontainer.clientWidth + 25 > document.body.clientWidth)
		x -=  hintcontainer.clientWidth + 35

	var resy = e.clientY+hintcontainer.clientHeight + 70
	if(resy > document.body.clientHeight)
		y -= resy - document.body.clientHeight

	hintcontainer.style.top =  y+"px"
     //hintcontainer.style.top =  (e.clientY+document.documentElement.scrollTop+2)+"px";
	hintcontainer.style.left =  x+"px"
     //hintcontainer.style.left = (e.clientX+document.documentElement.scrollLeft+10)+"px";
	hintcontainer.style.display="";
	/*if($(hintcontainer).css('display'=='none'))
		$(hintcontainer).fadeIn(100);*/
 }
 function hidehint() {  
    hintcontainer.style.display="none";
	//$(hintcontainer).fadeOut('fast');
 }

 function mvhint() {

	var scrollLeft = window.pageXOffset || document.documentElement.scrollLeft || 0;
	var scrollTop = window.pageYOffset || document.documentElement.scrollTop || 0;

	var x = pt.x+20 + scrollLeft
	var y = pt.y+20 + scrollTop

	var w,h
	var idata = pt.db[pt.o.id]
	w = idata.tw + 15
	h = idata.th + 90
	/*if($(hintcontainer).css('display')=='none'){
		var img = $('img', hintcontainer).get(0)
		w = img.width + 15
		h = img.height + 80
	}
	else{
		w = hintcontainer.clientWidth
		h = hintcontainer.clientHeight
	}*/

	if(pt.x+ w + 10 > $(window).width())
		x -=  w + 35

	var resy = pt.y+ h + 30
	if(resy > $(window).height())
		y -= resy - $(window).height()

	$(hintcontainer).css('top', y)
	$(hintcontainer).css('left', x)

}
function thumb_size(w,h){
	var sz = 380, wn = 0, hn = 0
    if(w > h) {
        hn = Math.round(h/(w/sz))
        wn = sz
    }
    else if(h > w) {
        wn = Math.round(w/(h/sz))
        hn = sz
    }
    else wn = hn = sz
    return [wn, hn]
}
function calc_thumb_size(idata){
	if (idata != undefined) if (idata.tw == undefined || idata.th == undefined){
		var tsz = thumb_size(idata.w, idata.h)
		idata.tw = tsz[0]
		idata.th = tsz[1]
	}
}
function update_hint(idata){
	$('#h_thumb').attr('src', pt.o.src).attr('width', idata.tw).attr('height', idata.th)
	$('#h_nail').replaceWith('<img src='+ idata.thumb +' id="h_nail" />')
	$('#h_text').css('width', idata.tw)
	$('#h_title').html(idata.title)
	$('#h_descr').html(idata.descr)
	$('#h_size').text(idata.w +' x '+ idata.h +' ('+ idata.mp +' MP)')
	$('#h_author').text(idata.author)

}
function update_hint_home(idata){
	$('#h_thumb').attr('src', pt.o.src).attr('width', idata.tw).attr('height', idata.th)
	$('#h_nail').replaceWith('<img src='+ idata.thumb +' id="h_nail" />')
	$('#h_text').css('width', idata.tw)
	$('#h_descr').html(idata.descr)
}
function inithint() {
	var idata = pt.db[pt.o.id]
	calc_thumb_size(idata)
	pt.updfn(idata)
	mvhint()
	//hintcontainer.style.display = ''
	if (pt.o != null) $(hintcontainer).fadeIn('fast');
 }

var pt = {x:0, y:0, o:null, updfn: update_hint}

function snap(x, y, ob){
	pt.x = x
	pt.y = y
	pt.o = ob
}

function checkhint(e){
	if (!e) e = event; //line for IE compatibility
	snap(e.clientX, e.clientY, this)
	if (!$(this).data('bound')) {
		$(this).mousemove(function(e){
			if (!e) e = event;
			snap(e.clientX, e.clientY, this)
			if(hintcontainer.style.display == 'block')
				mvhint();
		}).mouseout(function(){
			hintcontainer.style.display="none"
			pt.o = null
		})
		.data('bound', true);
	}
	var self = this
	setTimeout(function(){cmp_and_show(self)}, 300)
}

function cmp_and_show(elem) {
	if(pt.o == elem) inithint()
}

function getPX(e,pox) {
	if (!e) e = event;
	var scrollLeft = window.pageXOffset || document.documentElement.scrollLeft || 0;
	var mx = e.clientX + scrollLeft + pox;
	return mx;
}
function getPY(e,pox) {
	if (!e) e = event;
	var scrollTop = window.pageYOffset || document.documentElement.scrollTop || 0;
	var my = e.clientY + scrollTop + pox;
	return my;
}
var tm10;
function showPH(e,name) {
	clearTimeout(tm10)
	if (!e) e = event
	var tmp_hint = $('#'+name).appendTo(document.body).get(0)
	$('#'+name).css('position', 'absolute').css('top', getPY(e,10)).css('left', getPX(e,10)).css('margin', 0)
	tm10 = setTimeout("$('#"+name+"').fadeIn(150)", 500)
}
function hidePH(e,name) {
	clearTimeout(tm10)
	if (!e) e = event
	$('#'+name).fadeOut(100)
}
function setPosition(id,prT,prL) {
	pTop = (document.documentElement.scrollTop || document.body.scrollTop) + Math.round(prT * (document.documentElement.offsetHeight || document.body.clientHeight) / 100);
	pLeft = (document.documentElement.scrollLeft || document.body.scrollLeft) + Math.round(prL * (document.documentElement.offsetWidth || document.body.clientWidth) / 100);
	$('#'+id).css('top', pTop)
	$('#'+id).css('left', pLeft)
}
function setPositionMod(id,prT,prL) {
	pTop = Math.round(prT * (document.documentElement.offsetHeight || document.body.clientHeight) / 100);
	pLeft = Math.round(prL * (document.documentElement.offsetWidth || document.body.clientWidth) / 100);
	$('#'+id).css('top', pTop)
	$('#'+id).css('left', pLeft - Math.round($('#'+id).width() / 2))
	$('#'+id).css('margin-left', 0)
}
/**
 * Set element by id in the center of window or of passed element
 * @requires jQuery
 * @returns false if the input param is incorrect or jQuery object of element
 * vv
 */
$.fn.setPositionCenter = function(room) {
	var roomH = (room === undefined) ? $(window).height() : room.outerHeight(),
		roomW = (room === undefined) ? $(window).width() : room.outerWidth(),
		el = $(this),
		elH = el.outerHeight(),
		elW = el.outerWidth(),
		top = Math.round((roomH - elH) / 2);
	if (top < 0) {top = 0;}
	var left = Math.round((roomW - elW) / 2);
	el.css('top', top).css('left', left).css('margin', 0);
	return el;
}
function getHeightWin() {
	pHeight = (document.documentElement.offsetHeight || document.body.clientHeight);
	return pHeight;
}
function getWidthWin() {
	pWidth = (document.documentElement.offsetWidth || document.body.clientWidth);
	return pWidth;
}

function WinKeyPress() {
	$('.kpe').keydown(function(e){
		if (!e) e = event
		id = $(this).attr('id')
		if (e.keyCode == 13) $('#' + id + ' .kpe13').click()
		if (e.keyCode == 27) $('#' + id + ' .kpe27').click()
	})
}

function ITDset(obj,id) {
	if ($(obj).attr('value') == '') $(id).show()
}
function ITDunset(obj,id) {
	$(id).hide()
	obj.focus()
}
function ITDcl(id1,id2) {
	ITDunset($(id1),id2)
}

/*
 * Search hints widget by Depositphotos
 *
 * @depends on jQuery 1.4 && jQuery UI
 * @author vv
 * @data 10.05.2011
 *
 */
(function( $, undefined ) {

$.widget("ui.searchHints", {

	timer: null,
	previousValue: null,
	$wrap: null,
	$caller: null,

	options: {
		clip: {left: 0,	right: 0},
		templateSelector: '#search_hints',
		clientLang: 'en',
		delayTime: 200,
		withoutPhrases: false,
		animationSpeed: {
			hide: 100,
			show: 100
		}
	},

	_init: function(){
		this.$caller = this.element;
		this.$caller.attr('autocomplete', 'off').css('outline', 'none');
		this.$wrap = $(this.options.templateSelector).clone();
		this._prerender();
		this._append();
		this._position();
		this._followCallerOnResize();
		this._bindEvents();
	},
	_prerender: function(){
		if (this.options.withoutPhrases) {
			this.$wrap.find('.section-p').hide();
			this.$wrap.find('.bottom_bar').hide();
		}
	},
	_position: function(){
		this.$wrap.css({
			top: this.$caller.offset().top + this.$caller.outerHeight() - 1,
			left: this.$caller.offset().left + this.options.clip.left,
			width: this.$caller.outerWidth() - this.options.clip.right - parseInt(this.$caller.css('borderLeftWidth')) - parseInt(this.$caller.css('borderRightWidth'))
		});
	},
	_append: function(){
		this.$wrap.appendTo(document.body);
	},
	_followCallerOnResize: function(){
		var _this = this;
		$(window).resize(function(){
			_this._position();
		});
	},
	_bindEvents: function(){

		var _this = this;

		_this.$caller.bind('blur', function(){
			// TODO: replace with cron
			setTimeout(function(){
				_this._hide();
			}, 250);
		});

		_this.$caller.bind('focus', function(e){
			_this._call(true);
		});

		_this.$caller.bind('search', function(event, text){
			if (text) _this.$caller.val(text);
			_this.$caller.closest('form').find('input:submit, #search_submit_link').click();
		});

		_this.$caller.bind('redirect', function(event, link){
			window.location.href = link;
		});

		_this.$wrap.find('.bottom_bar-p-a').bind('click', function(){
			_this.$caller.trigger('search', _this.$caller.val());
		});

		_this._bindKeyEvents();

	},
	_bindKeyEvents: function(){

		var _this = this;

		_this.$caller.bind('keydown', function(e){

			if (e.keyCode == 13 && _this.$wrap.find('#search_hints_sellers .hint-item-selected').length) {

				if (_this.options.withoutPhrases) {
					_this.$caller.trigger('search', _this.$wrap.find('#search_hints_sellers .hint-item-selected .hint-item-right-p').text());
				} else {
					_this.$caller.trigger('redirect', _this.$wrap.find('#search_hints_sellers .hint-item-selected').attr('seller-url'));
				}

				return false;
			}

			if (e.keyCode == 13) {
				_this._hide();
			}

			if (e.keyCode == 27) {
				_this._hide();
				return false;
			}

		});

		_this.$caller.bind('keyup input', function(e){

			if (e.keyCode == 38 || e.keyCode == 40) {

				var hintPhraseCount = _this.$wrap.find('#search_hints_phrases .hint-item').length,
					hintSellerCount = _this.$wrap.find('#search_hints_sellers .hint-item').length,
					hintPhraseIndex = _this.$wrap.find('#search_hints_phrases .hint-item-selected').index(),
					hintSellerIndex = _this.$wrap.find('#search_hints_sellers .hint-item-selected').index(),
					selectIndex = 0;

				_this._hintCount = hintPhraseCount + hintSellerCount;

				if (hintPhraseIndex == -1 && hintSellerIndex !== -1) {
					_this._hintCurrentIndex = hintPhraseCount + hintSellerIndex;
				}
				else if (hintPhraseIndex !== -1) {
					_this._hintCurrentIndex = hintPhraseIndex;
				}
				else {
					_this._hintCurrentIndex = false;
				}

				// up
				if (e.keyCode == 38 ) {
					selectIndex = _this._hintCurrentIndex - 1;
					_this.$wrap.trigger('selectByIndex', _this._hintCurrentIndex ? selectIndex : _this._hintCount - 1);
				}

				// down
				if (e.keyCode == 40) {
					selectIndex = _this._hintCurrentIndex + 1;
					_this.$wrap.trigger('selectByIndex', _this._hintCurrentIndex === false || _this._hintCurrentIndex == _this._hintCount - 1 ? 0 : selectIndex);
				}

				return false;

			}

			_this._call();

		});

	},
	_bindLiveEvents: function(){

		var _this = this;

		_this.$wrap.find('.hint-item').bind('select', function(){
			_this.$wrap.find('.hint-item').removeClass('hint-item-selected');
			$(this).addClass('hint-item-selected');
		});

		_this.$wrap.find('#search_hints_phrases .hint-item').bind('click', function(e){
			_this.$caller.trigger('search', $(this).find('.hint-item-right-p').text())
		});

		_this.$wrap.find('#search_hints_sellers .hint-item').bind('click', function(e){
			if (_this.options.withoutPhrases) {
				_this.$caller.trigger('search', _this.$wrap.find('#search_hints_sellers .hint-item-selected .hint-item-right-p').text());
			} else {
				_this.$caller.trigger('redirect', $(this).attr('seller-url'));
			}
		});

		_this.$wrap.bind('selectByIndex', function(e, indexToSelect){
			var $hint = $(this).find('.hint-item').eq(indexToSelect);
			_this.element.val($hint.find('.hint-item-right-p').text());
			$hint.trigger('select');
		});

		_this.$wrap.find('.hint-item').bind('mouseenter', function(){
			$(this).trigger('select');
		});

	},
	_call: function(important){

		var _this = this;

		if (_this.previousValue === _this.$caller.val() && !important) return false;
		_this.previousValue = _this.element.val();

		_this._hide();

		if (_this.$caller.val().length < 3) {
			return false;
		}

		clearTimeout(_this.timer);
		_this.timer = setTimeout(function(){
			var localTimer = _this.timer;
			$.ajax({
				url: '/',
				type: 'POST',
				data: {need_hints_for: _this.$caller.val(), lang: _this.options.clientLang, without_phrases: _this.options.withoutPhrases ? 1 : 0},
				dataType: 'json',
				success: function(response){
					if (localTimer !== _this.timer) return false;
					if (response.data.phrases || response.data.sellers) {
						var phrasesHTMLString = '',
							sellersHTMLString = '';
						if (response.data.phrases) {
							var phrases = response.data.phrases;
							for (var i in phrases) {
								phrasesHTMLString += _this._renderHintPhrase(phrases[i]);
							}
							_this.$wrap.find('#search_hints_phrases .section-wrap').html(phrasesHTMLString).parent().show();
						}
						if (response.data.sellers) {
							var sellers = response.data.sellers;
							for (var ii in sellers) {
								sellersHTMLString += _this.options.withoutPhrases ?  _this._renderHintSellerShort(sellers[ii]) : _this._renderHintSeller(sellers[ii]);
							}
							_this.$wrap.find('#search_hints_sellers .section-wrap').html(sellersHTMLString).parent().show();
						}
						_this._show();
					} else {
						_this._hide();
					}
				},
				error: function(response){$.error(response);}
			});
		}, _this.options.delayTime);

	},
	_hide: function(){

		var _this = this;

		clearTimeout(_this._timer);
		_this.$wrap.fadeOut(_this.options.animationSpeed.hide, function(){
			_this.$wrap.find('.section-wrap').html('');
			_this.$wrap.find('.section').hide();
		});
	},
	_show: function(){
		this._bindLiveEvents();
		this._cropCachedThumbs();
		this.$wrap.find('#search_hints_prefix').text(this.$caller.val());
		this.$wrap.find('.g-with-hint').unbind('hover').bindHints();
		this.$wrap.fadeIn(this.options.animationSpeed.show);
	},
	_cropCachedThumbs: function(){

		var _this = this;

		_this.$wrap.find('.hint-item-left img').each(function(){

			if (this.width == 38 && this.height == 38) return;

			$(this).one('load', function(){

				var imageWidth = this.width,
					imageHeight = this.height;

				if (imageWidth > imageHeight) {
					$(this).css({height: 38, left: (-1 * Math.round(imageWidth / 2)) + 'px'});
				} else {
					$(this).css({width: 38, top: (-1 * Math.round(imageHeight / 2)) + 'px'});
				}

			});
		});

		_this.$wrap.find('.hint-item-left img').each(function(){
			if (this.complete) $(this).trigger('load');
		});
	},
	_renderHintPhrase: function(data){
		return '<div class="hint-item clearfix"><div class="hint-item-left"><img src="'+data.previewThumbUrl+'" alt="" /></div><div class="hint-item-right"><p class="hint-item-right-p"><span>'+data.phraseMatched+'</span>'+data.phraseSuggestion+'</p><span class="hint-item-right-span"><i18n>Search Results</i18n>: '+data.count+'</span></div></div>';
	},
	_renderHintSeller: function(data){
		return '<div class="hint-item hint-item-seller clearfix" seller-url="'+data.sellerUrl+'"><div class="hint-item-left"><img src="'+data.avatar+'" alt=""/></div><div class="hint-item-right"><p class="hint-item-right-p"><span>'+data.phraseMatched+'</span>'+data.phraseSuggestion+'</p><span class="hint-item-right-span">'+data.sellerInfo+'  |  <i18n>Online Files</i18n>: '+data.onlinePhotos+'</span><div class="hint-item-right-level g-with-hint" id="seller_level'+data.sellerLevelIndex+'" style="background-position: 0 '+data.sellerLevelIndex*-16+'px;"></div></div></div>';
	},
	_renderHintSellerShort: function(data){
		return '<div class="hint-item hint-item-seller clearfix" seller-url="'+data.sellerUrl+'"><div class="hint-item-left"><img src="'+data.avatar+'" alt=""/></div><div class="hint-item-right"><p class="hint-item-right-p"><span>'+data.phraseMatched+'</span>'+data.phraseSuggestion+'</p><span class="hint-item-right-span"><i18n>Online Files</i18n>: '+data.onlinePhotos+'</span></div></div>';
	}

});

})(jQuery);
