$(document).ready(function(){

  $('.a-disabled').live('click', function(){
	return false;
  });
  var userAgent = navigator.userAgent.toLowerCase();
  $.browser.chrome = /chrome/.test(userAgent);
  $.browser.safari = /webkit/.test(userAgent) && !/chrome/.test(userAgent);
  $('.custom-checks input').customInput();
  $('div.custom-radios input').customInput();

	/* Change languages */
//	$('a.changelang').bind('click', function(e){
//		e.preventDefault();
//		if ($(this).hasClass('switchToEnglish')) {
//			$.cookie('lang', 'en', {expires: 90, domain: '.depositphotos.com', path: '/'});
//			document.location.href = $(this).attr('basic-href') + document.location.pathname + document.location.search + document.location.hash;
//			return false;
//		}
//		document.location.href = $(this).attr('href') + document.location.pathname + document.location.search + document.location.hash;
//	});

	/* Popup windows handlers. @date 07.02.2011 vv */
	var zIndex = 3030;
	$('.g-popup').draggable({
		handle: '.g-popup-header',
		cancel: '.g-popup-close',
		opacity: $.browser.msie ? '' : '0.5',
		drag: function(evt, ui) {
			this.cachedHandler = this.cachedHandler || window[$(this).attr('draghandler')];

			if (this.cachedHandler != null)
				return this.cachedHandler.call(this, evt, ui);
		}
	});
	$(document).keydown(function(e) {
		if (e.keyCode == 27) {
			$('.g-popup').trigger('close');
		}
	});
	$('.g-popup').bind('close', function() {
		if ($.browser.msie) {
			$(this).closest('.g-popup').hide();
			$('.g-lock-layout').remove();
		}
		else {
			$(this).closest('.g-popup').fadeOut(100);
			$('.g-lock-layout').fadeOut(100, function(){$(this).remove()});
		}

		this.visible = false;
		shownWindowsList.remove(this);
	});
	$('.g-popup').bind('display', function() {
		if ($(this).hasClass('g-popup-lock') && !$('.g-lock-layout').length) {
			var $over = $('<div/>').addClass('g-lock-layout').css({
				zIndex: zIndex,
				width:$(document).width()+'px',
				height:$(document).height()+'px'
			});
			$over.appendTo(document.body);

			if ($.browser.msie && parseInt($.browser.version) == 9)
				$over.css('position', 'fixed');
		}
		$(this).appendTo(document.body);
		$(this).setPositionCenter().css('z-index', ++zIndex);

		if ($.browser.msie)
			$(this).show();
		else
			$(this).fadeIn(100);

		shownWindowsList.push(this);
		this.visible = true;
	});
	$('.g-popup .g-popup-close').bind('click', function(){
		$(this).closest('.g-popup').trigger('close');
	});
	$('.g-popup-trigger').bind('click', function() {
		var linkId = $(this).attr('id'),
			windowId = linkId.substr(0, linkId.indexOf('_trigger'));
		$('#'+windowId).trigger('display');
	});
	/* Hints. @date 09.02.2011 vv */
	$.fn.bindHints = function(){
		return $(this).each(function(){
			$(this).hover(function(){
				var hint_id = $(this).attr('id') + '_hint',
					_top = $(this).offset().top,
					_left = $(this).offset().left,
					_height = $(this).height(),
					_width = $(this).width();
				$('#'+hint_id).stop(true, true);
				$('#'+hint_id).appendTo(document.body);
				$('#'+hint_id).css({top: _top + _height, left: _left + _width}).fadeIn(200);
			}, function(){
				$('#'+hint_id).stop(true, true);
				var hint_id = $(this).attr('id') + '_hint';
				$('#'+hint_id).hide();
			});
		});
	};
	$('.g-with-hint').bindHints();
	/* Antisniff IE7 21.02.2011 vv */
	if ($.browser.msie && $.browser.version == '7.0') {
		$('.antisniff').each(function(){
			$(this).text($(this).attr('title'));
		});
	}

	$(document).keydown(function(evt) {
		if (evt.which == 13) {
			var lastShownWnd = shownWindowsList.slice(-1).pop();
			var found = false;

			$('.g-popup').each(function(idx, wnd) {
				if (this === lastShownWnd && this.visible) {
					var btns = $(this).find('.g-btn-green:visible');
					btns = btns.add($(this).find('.btn_gr:visible'));
					btns = btns.add($(this).find('.btn:visible'));

					if (btns.length > 0) {
						btns = $(btns.get(0));
					}

					if (btns.length == 1) {
						btns.click();

						evt.stopImmediatePropagation();
						evt.preventDefault();
						found = true;
					}

					return false;
				}
			})

			if (found)
				return false;
		}
	})

	var search_inputs = $('#sf_sbm, #sf2_sbm');
	var originalSubmit = search_inputs.closest('form').get(0);
	var originalSubmitFn = originalSubmit != null ? originalSubmit.submit : function() {};

	if (search_inputs.length) {
		search_inputs
			.each(function(idx, elem) {
				$(elem).attr('original-value', $(elem).val())
			})
			.bind('changeStatus', function() {
				var parent = $(this).parent();

				if ($(this).val() != '' || $(this).attr('original-value') != $(this).val())
					parent.addClass('changed');
				else
					parent.removeClass('changed');
			})
			.keyup(function() {
				$(this).trigger('changeStatus');
			})
			.trigger('changeStatus');
	}


	$('.search-btn-go').click(function() {
		$(this).closest('form').submit();

		return false;
	})

	$('.search-btn-clear').click(function() {
		var inp = $(this).parent().find('input');
		var orig = inp.attr('original-value');

		if (orig != inp.val() && orig == '') {
			inp.val('');

			inp.blur();
			inp.focus();
		}
		else {
			inp.val('');
			originalSubmitFn.call(originalSubmit);
		}

		inp.trigger('changeStatus');

		return false;
	})

	$('#search_submit_link').click(function() {
		originalSubmitFn.call(originalSubmit);

		return false;
	})

	$('<input type="hidden" value="1" name="submit" />').appendTo($('#search_form_start'));

});

function ImagesPreloader(path) {
	if (!~path.indexOf('/img/'))
		path = '/img/' + path;

	var image = new Image();

	image.onload = function() {
	}

	image.src = path;
}

new ImagesPreloader('exclude-icons.png');

var shownWindowsListCls = function() {
	this.remove = function(given) {
		for (var i = 0; i < this.length; i++) {
			var elem = this[i];

			if (elem === given) {
				this.splice(i, 1);
				break;
			}
		}
	}

	this.push_ = this.push;

	this.push = function() {
		var args = $.makeArray(arguments);
		args.push(this);

		if (!~$.inArray.apply($, args))
			this.push_.apply(this, arguments);
	}
}
shownWindowsListCls.prototype = new Array();
shownWindowsList = new shownWindowsListCls();

var fucking_flag = 1;
//#sel-search change handler
function change_sorting()
{
  try {if (fucking_flag==2) return true;} catch(e) {};
  var ss = window.location.search.replace(/\?/, '').split('&');
  var sn = ['sorting='+ this.value];
  var rp = /query=.+|search_photos=\d|search_vectors=\d|nudity=\d|id=\d/;
  for (i in ss){
    if(rp.test(ss[i]))
	sn.push(ss[i]);
  }
  window.location.hash = '';
  window.location.search = '?'+ sn.join('&');
}

function change_color(hex)
{
	document.getElementById('color').value=hex;
	document.getElementById('color_view').style.backgroundColor=hex;
	document.getElementById('color_view').style.backgroundImage='';
}

function update_color()
{
	if (document.getElementById('color').value.length!=7) return false;
	document.getElementById('color_view').style.backgroundColor=document.getElementById('color').value;
	document.getElementById('color_view').style.backgroundImage='';
}

function unset_color()
{
	document.getElementById('color_view').style.backgroundColor='';
	document.getElementById('color_view').style.backgroundImage='url(img/no_color.jpeg)';
	document.getElementById('color').value='';
}

function asf_change_color(hex,num) {
	$('#color-'+num).attr('value',hex)
	$('#color_view-'+num).css('background-color', hex)
	$('#color_view-'+num).css('background-image', 'url()')
	CHinput()
}
function asf_update_color(num) {
	if ($('#color-'+num).attr('value').length != 7) return false;
	$('#color_view-'+num).css('background-color', $('#color-'+num).attr('value'))
	$('#color_view-'+num).css('background-image', 'url()')
	CHinput()
}
function asf_unset_color(num) {
	$('#color_view-'+num).css('background-color', '')
	$('#color_view-'+num).css('background-image', 'url(img/no_color.jpeg)')
	$('#color-'+num).attr('value', '')
	CHinput()
}

function update_open_advanced_search()
{
	var open_advanced_search = document.getElementById('open_advanced_search')
	if (open_advanced_search.value==0) open_advanced_search.value=1;
	else if (open_advanced_search.value==1) open_advanced_search.value=0;
}

function setup_searchbox_hints() {
	var thisFn = arguments.callee;

	if (!thisFn.applied)
		thisFn.applied = true;
	else
		return;

	$(function(){
		$('.sbtn').hover(
			function(e) {
				showPH(e, 'shpop')
			},
			function(e) {
				hidePH(e, 'shpop')
			}
		)
	})
}

function CHinput() {
	var ar_ch = $('.ch-inp')
	if (ar_ch.length) {
		for (i=0; i<ar_ch.length; i++) {
			$(ar_ch[i]).removeClass('change_inp')
			if ($(ar_ch[i]).attr('type') == 'text') {
				if ($(ar_ch[i]).attr('value').length)
					$(ar_ch[i]).addClass('change_inp');

				$(ar_ch[i]).attr('original-value', $(ar_ch[i]).val());
			}
			if ($(ar_ch[i]).attr('type') == 'select-one') {
				if ($(ar_ch[i]).attr('value').length) {
					$(ar_ch[i]).addClass('change_inp');

					if ($(ar_ch[i]).attr('name') == 'limit' && $(ar_ch[i]).attr('value') == 40)
						$(ar_ch[i]).removeClass('change_inp');

					if ($(ar_ch[i]).attr('name') == 'orientation' && $(ar_ch[i]).attr('value') == 'all')
						$(ar_ch[i]).removeClass('change_inp');

					if ($(ar_ch[i]).attr('name') == 'sorting' && $(ar_ch[i]).attr('value') == 'best_match')
						$(ar_ch[i]).removeClass('change_inp');
				}
			}
		}
	}
}

function LocalFix(st, params) {
	window.location.href = '#st=' + st + params;
	return false;
}

function textDot(x1, x2, iter, pox, suf, sub) {
	var $x1 = $(x1)
	if (sub != 0) $x1.text($x1.text().substr(0, sub))
	$x1.text($x1.text() + suf)
	for (j=0; j<iter; j++) {
		$x1.text($x1.text().substr(0, $x1.text().length - (suf.length + 1)))
		$x1.text($x1.text() + suf)
		if ($x1.width() < ($(x2).width() - pox)) break
	}
}

function ChangeClass() {
	if ($(this).hasClass('checked')) {
		$(this).find('span').removeClass('fs-sn').addClass('fs-s')
	} else {
		$(this).find('span').removeClass('fs-s').addClass('fs-sn')
	}
}

(function( $ ){
	$.fn.cut_text = function(delim, els)
	{
		while($(this).attr('scrollWidth') > $(this).width())
		{
			var max_width = 0;
			var max_width_el = null;

			els.each(function(){
				if($(this).width() > max_width)
				{
					max_width = $(this).width();
					max_width_el = this;
				}
			});

			if(!max_width)
			{
				return;
			}

			var text = $(max_width_el).text();
			for(i=0;i<delim.length;i++)
			{
				var delim_esc = delim[i].replace(/[-[\]{}()*+?.,\\^$|#\s]/g, "\\$&");
				var regex = new RegExp("\\s+"+delim_esc+"\\s+.+", "i");
				text2 = text.replace(regex, "");
				if(text != text2)
				{
					$(max_width_el).text(text2)
					break;
				}
			}
			if(text == $(max_width_el).text())
			{
				return;
			}
		}
	};

	$.fn.max_height = function()
	{
		var max = 0;
		this.each(function() {
			max = Math.max( max, $(this).height() );
		});
		return max;
	};

	// placeholder
	$.extend($.support, { placeholder: !!('placeholder' in document.createElement('input')) });
	$.extend(jQuery.expr[':'], {focus: function(e){ return e == document.activeElement;} });
	$.fn.placeholder = function(checkAutofill) {
		return this.each(function() {
			if ($.support.placeholder) {return false;}
			if (this.tagName.toLowerCase() !== 'input' && this.tagName.toLowerCase() !== 'textarea') {return true;}
			var $this = $(this),
				ph = this.getAttribute('placeholder');
			if (!ph) {return true;}

			var $placeholder = $('<label style="position:absolute;display:none;cursor:text;" class="placeholder"></label>').css({
				fontSize: $this.css('fontSize'),
				top: parseInt($this.css('paddingTop')) + parseInt($this.css('borderTopWidth')) + ($.browser.msie && $.browser.version == 7 ? 1 : 0),
				left: parseInt($this.css('paddingLeft')) + parseInt($this.css('borderLeftWidth')) + ($.browser.msie ? 0 : 1)
			}).text(ph),
				$wrap = $('<div class="non-html5-holder" style="display:inline-block;position:relative;margin:0;padding:0;"></div>');

			$this.wrap($wrap);

			$placeholder.insertAfter($this);

			$placeholder.bind('click', function(){$this.trigger('focus')});

			$this.bind('firePlaceHolder', function(){
				if ($this.val()) {$placeholder.hide();}
				else {$placeholder.show();}
			});

			$this.bind('focus', function() {$placeholder.hide()});
			$this.bind('blur', function() {if (!$this.val()) {$placeholder.show();}});
			$this.bind('change', function(){$this.trigger('firePlaceHolder');});

			$this.trigger('firePlaceHolder');

			if (checkAutofill && (($.browser.msie && (!$.support.placeholder || $.browser.version < 9)) || $.browser.mozilla)) {
				cron.add(function(){
					if ($this.is(":focus")) {return false;}
					$this.trigger('firePlaceHolder');
				}, 500);
			}
		});
	};

})( jQuery );

var cron = {
	_events: [],
	_is_running: false,
	_timer: 0,
	_lastrun: 0,
	_delay: 0,
	_curtime: 0,

	getTime: function() {
		if (cron._curtime == 0) cron._curtime = new Date;
		cron._curtime.constructor();
		return cron._curtime.valueOf();
	},

	add: function(callback, interval) {
		if (this._delay > interval || this._delay == 0) {
			this.stop();
			this._delay = interval;
		}

		this._events.push({
			'callback': callback,
			'interval': interval,
			'timer': interval
		});

		this.run();
	},

	stop: function() {
			if (isNaN(cron._events.length)) return;

			for (var k in cron._events) {
				this._events[k].timer -= this.getTime()-this._lastrun;
			}

			this._lastrun = cron.getTime();
			clearTimeout(this._timer);
			cron._is_running = false;
	},

	run: function() {
		if (isNaN(cron._events.length)) return;
		if (cron._is_running) return;

		this._is_running = true;
		cron._lastrun = cron.getTime();

		var _timestamp = (_timestamp ? _timestamp : new Date);

		for (var k in cron._events) {
			this._events[k].timer -= this._delay;
			if (this._events[k].timer <= 0) {
				this._events[k].callback.call();
				this._events[k].timer = this._events[k].interval;
			}
		}

		this._timer = setTimeout(function(){
			cron._is_running = false;
			cron.run();
		}, cron._delay);
	}
};

(function($, undefined){
	// big preview
	$.widget("ui.preview", {

		_create: function(){
			var _this = this;

			_this.$popupPreview = $('#popup_preview');
			_this.$popupPreview.appendTo(document.body);

			this.element.bind('click', function(e){
				e.preventDefault();
				_this._display();
			});
		},

		_display: function(){
			var _this = this;

			_this.$popupPreview.one('display', function(){
				var alt = _this.element.attr('preview-alt'),
					title = _this.element.attr('preview-title'),
					href = _this.element.attr('href');


				_this.$popupPreview.find('.g-popup-title span').html(title);

				var $this = $(this),
					_content = $('.g-popup-content', $this),
					$img = $('<img/>'),
					withLoveForIe = $.browser.msie ? '?r='+(new Date()).getTime() : '';

				_content.html('<img src="/img/loading.gif" alt="">');
				$this.setPositionCenter();
				$img.attr('src', href + withLoveForIe);
				$img.attr('alt', alt);
				$img.attr('title', title);
				$img.bind('error', function() {
					_content.html('').append("<i18n>Error. No preview.</i18n>");
				});
				$img.one('load', function() {
					_content.html('').append($(this));
					_content.width($(window).width() / 1.5);
					_content.height($(window).height() / 1.3);
					if ($(window).width() > $(window).height()) {
						if ($img.height() < _content.height()) {_content.height($img.height());}
						else {$img.height(_content.height());$img.css('width','auto');}
						_content.width($img.width());
					}
					else {
						if ($img.width() < _content.width()) {_content.width($img.width());}
						else {$img.width(_content.width());$img.css('height', 'auto');}
						_content.height($img.height());
					}
					$this.width(_content.width() + 22);
					$this.setPositionCenter();
				});
			});
			_this.$popupPreview.trigger('display');
		}
	});
})(jQuery);
$().ready(function(){
	$('.g-preview').preview();
});


var dateFormat = function () {
	var	token = /d{1,4}|m{1,4}|yy(?:yy)?|([HhMsTt])\1?|[LloSZ]|"[^"]*"|'[^']*'/g,
		timezone = /\b(?:[PMCEA][SDP]T|(?:Pacific|Mountain|Central|Eastern|Atlantic) (?:Standard|Daylight|Prevailing) Time|(?:GMT|UTC)(?:[-+]\d{4})?)\b/g,
		timezoneClip = /[^-+\dA-Z]/g,
		pad = function (val, len) {
			val = String(val);
			len = len || 2;
			while (val.length < len) val = "0" + val;
			return val;
		};

	return function (date, mask, utc) {
		var dF = dateFormat;

		if (arguments.length == 1 && Object.prototype.toString.call(date) == "[object String]" && !/\d/.test(date)) {
			mask = date;
			date = undefined;
		}

		date = date ? new Date(date) : new Date;
		if (isNaN(date)) throw SyntaxError("invalid date");

		mask = String(dF.masks[mask] || mask || dF.masks["default"]);

		if (mask.slice(0, 4) == "UTC:") {
			mask = mask.slice(4);
			utc = true;
		}

		var	_ = utc ? "getUTC" : "get",
			d = date[_ + "Date"](),
			D = date[_ + "Day"](),
			m = date[_ + "Month"](),
			y = date[_ + "FullYear"](),
			H = date[_ + "Hours"](),
			M = date[_ + "Minutes"](),
			s = date[_ + "Seconds"](),
			L = date[_ + "Milliseconds"](),
			o = utc ? 0 : date.getTimezoneOffset(),
			flags = {
				d:    d,
				dd:   pad(d),
				ddd:  dF.i18n.dayNames[D],
				dddd: dF.i18n.dayNames[D + 7],
				m:    m + 1,
				mm:   pad(m + 1),
				mmm:  dF.i18n.monthNames[m],
				mmmm: dF.i18n.monthNames[m + 12],
				yy:   String(y).slice(2),
				yyyy: y,
				h:    H % 12 || 12,
				hh:   pad(H % 12 || 12),
				H:    H,
				HH:   pad(H),
				M:    M,
				MM:   pad(M),
				s:    s,
				ss:   pad(s),
				l:    pad(L, 3),
				L:    pad(L > 99 ? Math.round(L / 10) : L),
				t:    H < 12 ? "a"  : "p",
				tt:   H < 12 ? "am" : "pm",
				T:    H < 12 ? "A"  : "P",
				TT:   H < 12 ? "AM" : "PM",
				Z:    utc ? "UTC" : (String(date).match(timezone) || [""]).pop().replace(timezoneClip, ""),
				o:    (o > 0 ? "-" : "+") + pad(Math.floor(Math.abs(o) / 60) * 100 + Math.abs(o) % 60, 4),
				S:    ["th", "st", "nd", "rd"][d % 10 > 3 ? 0 : (d % 100 - d % 10 != 10) * d % 10]
			};

		return mask.replace(token, function ($0) {
			return $0 in flags ? flags[$0] : $0.slice(1, $0.length - 1);
		});
	};
}();

dateFormat.masks = {
	"default":      "ddd mmm dd yyyy HH:MM:ss",
	shortDate:      "m/d/yy",
	mediumDate:     "mmm d, yyyy",
	longDate:       "mmmm d, yyyy",
	fullDate:       "dddd, mmmm d, yyyy",
	shortTime:      "h:MM TT",
	mediumTime:     "h:MM:ss TT",
	longTime:       "h:MM:ss TT Z",
	isoDate:        "yyyy-mm-dd",
	isoTime:        "HH:MM:ss",
	isoDateTime:    "yyyy-mm-dd'T'HH:MM:ss",
	isoUtcDateTime: "UTC:yyyy-mm-dd'T'HH:MM:ss'Z'"
};

dateFormat.i18n = {
	dayNames: [
		"Sun", "Mon", "Tue", "Wed", "Thu", "Fri", "Sat",
		"Sunday", "Monday", "Tuesday", "Wednesday", "Thursday", "Friday", "Saturday"
	],
	monthNames: [
		"Jan", "Feb", "Mar", "Apr", "May", "Jun", "Jul", "Aug", "Sep", "Oct", "Nov", "Dec",
		"January", "February", "March", "April", "May", "June", "July", "August", "September", "October", "November", "December"
	]
};

Date.prototype.format = function (mask, utc) {
	return dateFormat(this, mask, utc);
};

jQuery.cookie = function (key, value, options) {

    if (arguments.length > 1 && String(value) !== "[object Object]") {
        options = jQuery.extend({}, options);

        if (value === null || value === undefined) {
            options.expires = -1;
        }

        if (typeof options.expires === 'number') {
            var days = options.expires, t = options.expires = new Date();
            t.setDate(t.getDate() + days);
        }

        value = String(value);

        return (document.cookie = [
            encodeURIComponent(key), '=',
            options.raw ? value : encodeURIComponent(value),
            options.expires ? '; expires=' + options.expires.toUTCString() : '',
            options.path ? '; path=' + options.path : '',
            options.domain ? '; domain=' + options.domain : '',
            options.secure ? '; secure' : ''
        ].join(''));
    }

    options = value || {};
    var result, decode = options.raw ? function (s) { return s; } : decodeURIComponent;
    return (result = new RegExp('(?:^|; )' + encodeURIComponent(key) + '=([^;]*)').exec(document.cookie)) ? decode(result[1]) : null;
};
