var isIE6 = (navigator.userAgent.indexOf('MSIE 6') !== -1);

function scrollMe(el) {
	el = $(el);

	var f, init = el.offset().top, left = el.offset().left,
		max = $('#main_content').offset().top + $('#main_content').innerHeight();
	
	
	f = window.onscroll = document.documentElement.onscroll = function(e) {
		
		var t = document.documentElement.scrollTop || document.body.scrollTop;
		if (t < init) {
			return el.css({
				top : '10px',
				left : 'auto',
				position : 'relative'
			});
		}
		
		if (t >= init && t + el.outerHeight() + 15 <= max) {
			el.css({
				top : '10px',
				left : left + 'px',
				position :'fixed'
			});
		}
		else {
			el.css({
				top : $('#main_content').outerHeight() - el.outerHeight() + 'px',
				left : 0,
				position : 'absolute'
				
			});
		}
	};
	
	window.onresize = function(e) {

		left = $('#right_list').offset().left;
		if (el.css('position') === 'fixed')
			el.css({left : left + 'px'});
	}

	f();
}

function showSub (t, id) {
	$('#section2').css('display','block');
	$('.subs').each(function(index){
		if ($(this).css('display') != 'none')
			$(this).slideUp(500);	
	});
	$('#d' + id).slideDown(400);
	$('#section1 > a').add('#section2 > div > a').each(function(){
		$(this).removeClass('active');
	});
	$('#section3').css('display', 'none');
	$(t).addClass('active');
}

function showType (id, types, clicked) {
	
	
	$('#section2 > div > a').each(function(){
		$(this).removeClass('active');
	});
	$(clicked).addClass('active');

	
	$('#section3 > a').each(function(){
		$(this).css('display','none');
		
	});
	$('#section3').css('display','block');
	var t = types.split(',');
	for(var i in t) {
		$('#a' + t[i]).css('display','block');
		$('#a' + t[i]).attr('rel',id);
		 
	}
	
	return false;
}

function initRemoveImg(url) {
	$('div.img_cnt > a').each(function(){
		
		if (!$(this).attr('rel')) {
			
			$(this).click(function(e){
				if (confirm(window.userData.remove_image)) {
					$(this).html(window.userData.removing);
					var tmp = $(this).attr('id').split('a'),
						adId = tmp[1],
						imgId = tmp[0].replace('ri',''),
						rem = $(this).parent();
					
					rem.append('<img src="/images/loading.gif" class="loading"/>');
					
					$.ajax({
						url : url + '&i=' + imgId + '&a=' + adId,
						success : function(){
							rem.fadeOut('fast', function(){
								$(this).remove();
							});
					}});
				}
				return false;
			});
		}
	});
};

function goAdd (e, link) {
	window.location = link + '&subctg=' + e.rel;
	return false;
}

function lnt(e,id,init) {
	return init - $(id).attr('value').length;
}


function add2() {
	$('p.lnt').each(function(i){
		var label = $(this),
			id = $(this).attr('id').slice(1),
			init = $(this).html(),
			l = init - $('#' + id).attr('value').length;
		
		$(this).html(l).css({color : l < 0? 'red' : 'green'});
		
		
		$('#' + id).bind('keyup',function(){
			var l = init - this.value.length;
			$('#p' + id).html(l).css({color : (l <0)? 'red' : 'green'}); 
		
		});
	});
	
	$('input, textarea').bind('focus', function(){
		$(this.parentNode).children('.hint').addClass('active');
	});
	
	$('input, textarea').bind('blur', function(){
		$(this.parentNode).children('.hint').removeClass('active');
	});

	$('#add_phone').bind('click', function(e){addField(e, 'add_phone', '_phone', 'ad_phone');});
	$('#add_ad input[type="text"]').first().focus();
}

function fetchSubs(el, url) {
	if (isIE6)
		return;
	$.ajax({
		url : url + el.value,
		success : function(response){
			
			$('#ad_location').html(response);
		},
		error : function(e) {
			console.log(e);
		}
	});
}

function register() {
	

	$('#register input[type="text"]').first().focus();
}

function add3() {
	$('#add_image').bind('click', function(e){addField(e, 'add_image', '_image', 'ad_image');});
}

function showForm(el) {
	$('#add_ad').fadeIn(400);
	el.parentNode.parentNode.removeChild(el.parentNode);
}

function addImage(e) {
	e.preventDefault();
}

function addField(e, launcher, startContainer, fieldPrefix) {
	
	e.preventDefault();
	var old = $('#' + startContainer),
		i = parseInt(($('#' + startContainer + ' > input').attr('id').replace(fieldPrefix,''))),
		d = old.clone();
	
	$(old).attr('id','p' + (i+1));
	$('#' + launcher).remove();
	
	d.children().each(function(index){
		var tmp = $(this).attr('id').replace(i,i+1);
		$(this).attr('id', tmp);
		var tag = $(this).get(0).tagName.toLowerCase();
		
		if (tag == 'label') {
			tmp = $(this).attr('for').replace(i, i+1);
			$(this).attr('for', tmp);
			
		}
		if (tag == 'input') {
			tmp = $(this).attr('name').replace(i, i+1);
			$(this).attr('name', tmp);
			
			if ($(this).attr('type') == 'file') {
				var size = $(this).attr('size');
				$(this).replaceWith('<input type="file" id="' + (i + 1) + '" name="image_' + (i + 1) + '" size="' + size + '"/>');
			}
			else
				$(this).attr('value', '');
		}
	});
	
	d.css('display','none');
	old.after(d);
	
	var init = $('#p' + fieldPrefix + (i+1)).html();
	$('#' + fieldPrefix + (i+1)).bind('keyup',function(){
		$('#p' + fieldPrefix + (i+1)).html(init - this.value.length); 
	});

	
	
	d.fadeIn(300);
	$('#' + launcher).bind('click', function(e){addField(e, launcher, startContainer, fieldPrefix);});
	
	return false;
};


autocomplete = function(input, dataUrl) {
	var self = this;
	this.index = 0;
	
	$(input).bind('keyup focus', function(e) {self.fieldKeyPress(e);});
	$(input).bind('keydown keypress', function(e){if (e.which == 13) e.preventDefault();});
	$(document).bind('click', function(e){
		if ('#' + e.target.id != input) 
			$('#_aut').remove();
	});
	
	this.init = function() {
		if (!$('#_aut').get(0)) {
			$('body').append('<div id="_aut"></div>');
			var div = $('#_aut'),
				pos = $(input).position();
			
			div.css({
				top			: (pos.top + $(input).innerHeight()),
				left 		: pos.left,
				minWidth 	: $(input).innerWidth()
			});
			
			if (!$('#_autres').get(0)) {
				var hidden = '<input type="hidden" id="_autres"/>';
				$(input).after(hidden);
				$('#_autres').attr('name', $(input).attr('name') + '_id');
			}
		}
	};
	
	this.confirm = function (e) {
		e.preventDefault();
		
		if ($('#_aut > ._aut_active').html() != null) {
			var res = $('#_aut > ._aut_active').html().replace(/(<.*?>)/ig, "");
			var index = res.indexOf(' (');
			if (index != -1)
				res = res.substr(0, index);
			
			$(input).attr('value', res);
			$('#_autres').attr('value', $('#_aut > ._aut_active').attr('href'));
		}
		else
			$('#_autres').attr('value','');
		$('#_aut').remove();
	};
	
	
	this.fieldKeyPress = function(e) {
		this.init();
		switch (e.which) {
			case 38:
				var prev;
				prev = $('#_aut > ._aut_active').prev();
				if (typeof prev.get(0) == 'undefined') 
					prev = $('#_aut').children().last();
				if (this.index != 0)
					this.index.removeClass('_aut_active');
				this.index = prev;
				this.index.addClass('_aut_active');

				break;
			case 40:
				var next;
				next = $('#_aut > ._aut_active').next();
				if (typeof next.get(0) == 'undefined') 
					next = $('#_aut').children().first();
				if (this.index != 0)
					this.index.removeClass('_aut_active');
				this.index = next;
				this.index.addClass('_aut_active');
				break;
				
			case 13:
				e.preventDefault();
				this.index = 0;
				this.confirm(e);
				break;
			case 27:
				$('#_aut').remove();
				break;
			default :
				this.index = 0;
				$.ajax({
					dataType: "json",
					url: dataUrl + '?ajax=' + $(input).attr('value'),
					jsonp: "$callback",
					success: function(res){
						var it = '';
						$(res).each(function(index){
							it = it + '<a href="' + this.i + '">' + this.l + '</a>';
						});
						$('#_aut').html(it);
						$('#_aut > a').bind('mouseover', function(e){$(this).addClass('_aut_active');});
						$('#_aut > a').bind('mouseout', function(e){$(this).removeClass('_aut_active');});
						$('#_aut > a').bind('click', function(e){self.confirm(e);});
						
					}
				});
		}
	};
};

function MessageBox(url) {
	
	var overlay;
	var loading;
	var message;
	var f_resize;
	var self = this;
	
	if (isIE6) {
		try {
			window.location = window.event.srcElement.href;
		}
		catch(e) {};
	}
		
	
	this._init = function() {
		overlay = $('#overlay');
		if (typeof overlay.get(0) == 'undefined') {
			overlay = $('<div id="overlay"></div>');
			$('body').append(overlay);
			
			overlay.css({
				filter : 'alpha(opacity=0)',
				height : $(document).height()
			});
		}
		
		loading = $('#ajax_wrapper');
		if (typeof loading.get(0) == 'undefined') { 
			loading = $('<div id="ajax_wrapper"><img src="/images/loading.gif"/></div>');
			$('body').append(loading);
			
		}
		overlay.animate({
			'opacity' : 0.55
		},200, function(){
			
			loading.css({
				'left': ((overlay.width() - 70)/2) + 'px',
				'top' : '150px'
			});
			loading.fadeIn(300, function() {
				self.show(url, 'get', {});
			});
		});
		
	};
	
	
	this.show = function(url, method, params){
		
		if (!params)
			params = {ajax : 1};
		else
			params.ajax = 1;
		
		try{
		$.ajax({
			url		: url,
			data	: params,
			type	: method,
			success : function(response){
				
				message = $('#ajax_message');
				if (!message.get(0)) {
					message = $('<div id="ajax_message"></div>');
					$('body').append(message);
				}
				message.html(response);
				
				var script = $('#ajax_message script');
				
				if (script.get(0))
					eval(script.html());
				
				var container = $('#ajax_container');
				
				var f_close = function(e) {
					$(document).unbind('keyup', f_close);
					if (e.keyCode === 27)
						self.close();
				};
				
				$('#ajax_close, #overlay').bind('click', function() {self.close();});
				$(document).bind('keyup', f_close);
					
				$('#ajax_container_border').css({
					width : container.outerWidth() + 'px',
					height : container.outerHeight() + 'px'
				});
				
				
				f_resize = function(e) {
					message.css({
						left 	: Math.max(0, ((overlay.width() - container.outerWidth())/2)) + 'px',
						top 	:  Math.max(0, (($(window).height() - container.outerHeight())/4)) + 'px',
						width : container.outerWidth() + 20 + 'px',
						height : container.outerHeight() + 20 + 'px'
					});
				};
				
				$(window).bind('resize', f_resize);
				
				f_resize();
					
				loading.animate({
					opacity : 0
				},200, function(){
						
					$(message).animate({
						opacity : 1
					},300);
				});
				var found = false;
				$('#ajax_container input[type="text"], #ajax_container textarea').each(function(i){
					if (!found && !this.value) {
						this.focus();
						found = true;
					}
				});
			}
		});
		}
		catch(e) {
			console.log(e);
		}
	};
		
	
	
	this.close = function() {
		$('#ajax_message').fadeOut(300, function(){
			overlay.fadeOut(200, function(){
				overlay.remove();
				message.remove();
				loading.remove();
				$(window).unbind('resize', f_resize);
			});	
		});
	};
	
	this.submitForm = function (form) {
		if (isIE6)
			return form.submit();
		try {
			var submit = $('#ajax_container input[type="submit"]').first();
			submit.parent().append($('<img src="/images/loading.gif" class="ajax_load"/>'));
			submit.attr('disabled', 'disabled');
			
			var param = {ajax : 1};
					
			$('#' + form.id + ' input').each(function(){
				var v = $(this).attr('type');
				if ((v == 'radio' && $(this).attr('checked')) || v != 'radio')
					param[$(this).attr('name')] = $(this).attr('value');
			});
						
			$('#' + form.id + ' textarea').each(function(){
				param[$(this).attr('name')] = $(this).get(0).value;  
			});
			
			var act = $(form).attr('action');
				act = act.replace('http://', '');
				act = act.substr(act.indexOf('/'));
			
			window.messageBox.show(
				act,
				'post',
				param
			);
			
			return false;		
		}
		catch(e) {console.log(e);}
	};
	
	this._init();
	
}


function Fav () {
	var self = this,
		nChosen = $('#n_chosen');
	
 	this.choose = function(link) {
		choose(link);
		setCookie('chosen', window.chosenAds.toString(), 10, window.userData.cDomain);
		return false;
	};
	
	var choose = function(link){
		
		var id = link.id.replace('a',''),
			count = parseInt(nChosen.html()),
			index = window.chosenAds.search(id),
			str = window.userData.select,
			nCount = count - 1;
		
		if (index !== false) {
			
			window.chosenAds.splice(index, 1);
			$(link).removeClass('selected');
		}
		else {
			nCount = count + 1;
			window.chosenAds.push(id);
			str = window.userData.deselect;
			$(link).addClass('selected');
		}
		
		$(nChosen).fadeOut(100, function(){
			nChosen.html(nCount);
			$(nChosen).fadeIn(200);
		});
		
		$(link).fadeOut(100, function(){
			link.innerHTML = str;
			$(link).fadeIn(200);
		});
	};
	
	this.remove = function (el) {
		console.log(window.userData);
		if (confirm(window.userData.remove_ad)) {
			this.choose(el);
			
			el = $(el);
			
			while (!el.hasClass('ad_box')) {
				el = el.parent();
			}
			
					
			$(el).animate({
				opacity : 0,
				height : 0
			}, 300,  function(el){
				$(this).remove();
			});
		}
		
		return false;
	};
	
	this.clear = function() {
		if (confirm(window.userData.clear_favorites)) {
			$('#content .ad_box').add('#paginator').add('#headline a').each(function(i){
				$(this).animate({
					opacity : 0,
					height : 0
				}, 300,  function(){
					$(this).remove();
				});
			});
			$('#headline strong').html('&nbsp;');
			setTimeout(function(){
				var tmp = $('<p></p>').attr('class', 'info').html(window.userData.favorites_cleared).css({
					marginTop : '15px',
					marginBottom : '15px',
					opacity:0,
					height:0
				});
				
				$('#headline').after(tmp);
				$(tmp).animate({
					opacity : 1,
					height : '20px'
				}, 200);
			},350);
			
			setCookie('chosen', '', 10, window.userData.cDomain);
			window.chosenAds = [];
			nChosen.html(0);
		}
		
		return false;
	};
	
	
	var chosen = getCookie('chosen');
	
	window.chosenAds = (chosen)?
	chosen = chosen.split(',') : [];
}

Array.prototype.search = function(el){
	for (var i in this) {
		if (this[i] == el)
			return i;
	} 
	return false;
};


function setCookie(cName, value, expireDays, domain) {
	var exdate=new Date();
		exdate.setDate(exdate.getDate() + expireDays);
		
		document.cookie = cName + "=" + escape(value) +
		((expireDays == null) ? "" : ";expires=" + exdate.toUTCString()) +
		((domain == null) ? "" : ";domain=" + domain) + ';path=/';
}

function getCookie(cName) {
	if (document.cookie.length > 0) {
		cStart = document.cookie.indexOf(cName + "=");
		
		if (cStart != -1) {
			cStart = cStart + cName.length + 1;
			cEnd = document.cookie.indexOf(";",cStart);
			
			if (cEnd == -1) 
				cEnd = document.cookie.length;
			return unescape(document.cookie.substring(cStart,cEnd));
		}
	}
	
	return "";
}

function updateAd(adId) {
	if (!userData.updateMessage || !userData.urlBase)
		return false;
	
	
	if (confirm(userData.updateMessage)) {
		console.log('http://' + userData.urlBase + '/ad/update/?ad_id=' + adId);
		$.ajax({
			'url' : 'http://' + userData.urlBase + '/ad/update/?ad_id=' + adId,
			'success' : function(response){
				//console.log(response);
					window.location = response;
		}});
		return false;
	}
	
	return false;
}


function ph(t) {
	var s = $('#search_query');
	if (s.attr('placeholder') == s.attr('value')) {
		s.attr('value', '');
		s.addClass('act');
	}
	else
		if (t && !s.attr('value')) {
			s.attr('value', s.attr('placeholder'));
			s.removeClass('act');
		}
	
	if (t && !s.attr('value'))
		s.removeClass('act');
}

function buttons () {
	
	$('#btn input[type="radio"]').each(function(i){
		$(this).bind('click', function(e){
			$('#btn_code').html(sprintf(window.userData.btn_template,[this.value])); 
		});
	});
	
	$('#html').bind('click', function(e){
		$('#btn_code').html(window.userData.html_template);
	});
	
	$('#bb').bind('click', function(e){
		$('#btn_code').html(window.userData.bb_template);
	});
	
	$('textarea').bind('click', function(e){this.select();});
}

function sprintf(subj, values) {
	var p = subj.split('??');
	var res = ''; 
	for (var i=0;i<p.length;i++)
		res = res + p[i] + ((i < values.length)? values[i] : '');
	return res;
}









