var max_chars = 1000;

function ShowShortContent(par_Obj, par_ID, par_State) {
 l_Obj = document.getElementById(par_ID);

 if (par_State)
   tooltip(par_Obj, l_Obj.innerHTML);
     else
   hide_info(par_Obj);
}

function strip_tags (input, allowed) {
    // Strips HTML and PHP tags from a string  
    // 
    // version: 1103.1210
    // discuss at: http://phpjs.org/functions/strip_tags
    // +   original by: Kevin van Zonneveld (http://kevin.vanzonneveld.net)
    // +   improved by: Luke Godfrey
    // +      input by: Pul
    // +   bugfixed by: Kevin van Zonneveld (http://kevin.vanzonneveld.net)
    // +   bugfixed by: Onno Marsman
    // +      input by: Alex
    // +   bugfixed by: Kevin van Zonneveld (http://kevin.vanzonneveld.net)
    // +      input by: Marc Palau
    // +   improved by: Kevin van Zonneveld (http://kevin.vanzonneveld.net)
    // +      input by: Brett Zamir (http://brett-zamir.me)
    // +   bugfixed by: Kevin van Zonneveld (http://kevin.vanzonneveld.net)
    // +   bugfixed by: Eric Nagel
    // +      input by: Bobby Drake
    // +   bugfixed by: Kevin van Zonneveld (http://kevin.vanzonneveld.net)
    // +   bugfixed by: Tomasz Wesolowski
    // +      input by: Evertjan Garretsen
    // +    revised by: Rafał Kukawski (http://blog.kukawski.pl/)
    // *     example 1: strip_tags('<p>Kevin</p> <b>van</b> <i>Zonneveld</i>', '<i><b>');
    // *     returns 1: 'Kevin <b>van</b> <i>Zonneveld</i>'
    // *     example 2: strip_tags('<p>Kevin <img src="someimage.png" onmouseover="someFunction()">van <i>Zonneveld</i></p>', '<p>');
    // *     returns 2: '<p>Kevin van Zonneveld</p>'
    // *     example 3: strip_tags("<a href='http://kevin.vanzonneveld.net'>Kevin van Zonneveld</a>", "<a>");
    // *     returns 3: '<a href='http://kevin.vanzonneveld.net'>Kevin van Zonneveld</a>'
    // *     example 4: strip_tags('1 < 5 5 > 1');
    // *     returns 4: '1 < 5 5 > 1'
    // *     example 5: strip_tags('1 <br/> 1');
    // *     returns 5: '1  1'
    // *     example 6: strip_tags('1 <br/> 1', '<br>');
    // *     returns 6: '1  1'
    // *     example 7: strip_tags('1 <br/> 1', '<br><br/>');
    // *     returns 7: '1 <br/> 1'
    allowed = (((allowed || "") + "").toLowerCase().match(/<[a-z][a-z0-9]*>/g) || []).join(''); // making sure the allowed arg is a string containing only tags in lowercase (<a><b><c>)
    var tags = /<\/?([a-z][a-z0-9]*)\b[^>]*>/gi,
        commentsAndPhpTags = /<!--[\s\S]*?-->|<\?(?:php)?[\s\S]*?\?>/gi;
    return input.replace(commentsAndPhpTags, '').replace(tags, function ($0, $1) {
        return allowed.indexOf('<' + $1.toLowerCase() + '>') > -1 ? $0 : '';
    });
}

function send_seller_email(id) {
	jQuery.post('advert/send_seller_email/' + id + '.html');
	$('#send_seller_email_' + id).remove();
	$('#label_send_seller_email_' + id).html('Автору выслан e-mail с инструкциями по управлению данным объявлением (копия извещения о размещении объявления)');
}

function get_advert_preview() {
	if (!validate_advert_create_form()) {
		return;
	}
	var icq = '';
	if ($("#user_icq").val()) {
		icq = '<tr height="20"><td>' + lang["icq"] + ':</td><td>' + $("#user_icq").val() + '</td></tr>';
	}
	
	var website = '';
	if ($("#user_website").val()) {
		website = '<tr height="20"><td>' + lang["website"] + ':</td><td><a href="' + $("#user_website").val() + '">' + $("#user_website").val() + '</a></td></tr>';
	}
	
	var d = new Date();
    d.setDate(d.getDate() + parseInt($("#advert_period").val()));
    var month = d.getMonth() + 1;
	if (d.getMonth() < 10) {
		month = '0' + (d.getMonth() + 1);
	}
	var day = d.getDate();
	if (d.getDate() < 10) {
		day = '0' + d.getDate();
	}
	
	period = d.getFullYear() + '-' + month + "-" + day;

	body = $("#body").val();
	body = strip_tags(body);
	body = body.replace(/\[url\](.*?)\[\/url\]/gm, '<a href="$1">$1</a>');
	body = body.replace(/\[img\](.*?)\[\/img\]/gm, '<img src="$1" />');

	var images = '';
	var first = 0;
	if ($(".small_cached_image").length > 1) {
		images += '<div id="medium_image_new" style="background-image:url(ecms/cache/' + $(".medium_cached_image:first").val() + '); width:384px; height:288px;" class="medium_image"></div>';
		$(".small_cached_image").each(function(){
			var active = '';
			if (!first) {
				active = 'small_image_active';
				first++;
			}
			images += '<div class="small_image ' + active + '" onclick="load_medium_image(\'new\', this, \'' + $(this).val().replace("small", "medium") + '\')" style="background-image: url(ecms/cache/' + $(this).val() + '); width: 122px; height: 96px;"></div>';
		});
	} else if ($(".small_cached_image").length == 1) {
		images += '<div id="medium_image_new" style="background-image:url(ecms/cache/' + $(".medium_cached_image:first").val() + '); width:384px; height:288px;" class="medium_image"></div>';
	}
	
	var output = '<p style="font-size: 11px;">&nbsp;</p><span class="section_header">'+lang["preview_long"]+'</span><p>&nbsp;</p><table width="100%"> <tr valign="top"> <td width="80%"> <table width="100%"> <tr height="30"> <td width="20%">' + lang["part"] + ':</td> <td> <a href="http://ecms.nucleart.net/market.airsoft.ua/adverts/' + $("#select_folder0").val() + '">' + $("#select_folder0 option:selected").html() + '</a> &nbsp;/&nbsp; <a href="http://ecms.nucleart.net/market.airsoft.ua/adverts/' + $("#select_folder1").val() + '.html">' + $("#select_folder1 option:selected").html() + '</a> </td> </tr> <tr height="30"> <td>' + lang["type"] + ':</td> <td> ' + $("#advert_type option:selected").html() + ' </td> </tr> <tr> <td colspan="2"><h2 class="adv"><b>' + $("#title").val() + '</b></h2></td> </tr> <tr> <td colspan="2"> <div style="padding-bottom: 20px;">' + body + '</div> </td> </tr> <tr height="30"> <td>' + lang["price"] + ':</td> <td><b>' + $("#price").val() + '&nbsp;' + $("#currency option:selected").html() + '</b></td> </tr> <tr height="30"> <td>' + lang["author"] + ':</td> <td><u><strong>' + $("#user_name").val() + '</strong></u></td> </tr> <tr height="20"> <td>' + lang["city"] + ':</td> <td>' + $("#locations option:selected").html() + '</td> </tr> <tr height="20"> <td>' + lang["phone"] + ':</td> <td>' + $("#user_phone").val() + '</td></tr>' + icq + website + '<tr height="20"> <td>' + lang["placement_time"] + ':</td> <td>' + period + '</td> </tr> </table> </td> <td width="30%" nowrap=""><div class="shotsarchive">' + images + '</div> </td> <td width="200"> <div style="width: 200px; padding-right: 20px;"></div> </td> </tr> </table>';
	$('#advert_preview').hide().html(output).slideDown(200);
}

function load_medium_image(id ,s_image, m_image) {
	if (id == 'new') {
		$('#medium_image_' + id)
			.css('background-image', 'url(ecms/cache/' + m_image + ')');
	} else {
		$('#medium_image_' + id)
			.css('background-image', 'url(resources/advert/' + id + '/' + m_image + ')');
	}
	
	$('.small_image_active').removeClass('small_image_active');
	$(s_image).addClass('small_image_active');
}

function update_available_chars() {
	var available_chars = max_chars - $('#body').val().length;
	if($('#body').val().length  > max_chars) {
		$('#body').val($('#body').val().substr(0, max_chars));
	} else {
		$('#available_chars').html(available_chars);
	}
}

function validate_advert_create_form(update) {
	var error = new Array;
	
	if ($('#select_folder0').val() == 0) {
		$('#label_structure').html(lang.must_be_not_empty);
		error.push('part');
	} else {
		$('#label_structure').html('');
	}
	
	if ($('#select_folder1').val() == 0) {
		$('#label_substructure').html(lang.must_be_not_empty);
		error.push('subsection');
	} else {
		$('#label_substructure').html('');
	}
	
	if ($('#advert_type').val() == -1) {
		$('#label_advert_type').html(lang.must_be_not_empty);
		error.push('type');
	} else {
		$('#label_advert_type').html('');
	}
	
	if ($('#user_name').val() == '') {
		$('#label_user_name').html(lang.must_be_not_empty);
		error.push('name');
	} else {
		$('#label_user_name').html('');
	}
	
	if ($('#user_email').val() == '') {
		$('#label_user_email').html(lang.must_be_not_empty);
		error.push('email');
	} else {
		var reg_email = /^([A-Za-z0-9_\-\.])+\@([A-Za-z0-9_\-\.])+\.([A-Za-z]{2,4})$/;
		if (reg_email.test($('#user_email').val())) {
			$('#label_user_email').html('');
		} else {
			$('#label_user_email').html(lang.incorrect_email);
			error.push('email');
		}
	}

	if ($('#user_phone').val() == '') {
		$('#label_user_phone').html(lang.must_be_not_empty);
		error.push('phone');
	} else {
		var reg_phone = /^\+(([\d]{2})) \(([\d]{3})\) ([\d]{3})-([\d]{2})-([\d]{2})$/;
		if (reg_phone.test($('#user_phone').val())) {
			$('#label_user_phone').html('');
		} else {
			$('#label_user_phone').html(lang.incorrect_phone);
			error.push('phone');
		}
	}

	if ($('#locations').val() == 0) {
		$('#label_locations').html(lang.must_be_not_empty);
		error.push('city');
	} else {
		$('#label_locations').html('');
	}
	
	if ($('#price').val() == '') {
		$('#label_price').html(lang.must_be_not_empty);
		error.push('price');
	} else {
		var reg_num = /^\d+$/;
		if (reg_num.test($('#price').val())) {
			$('#label_price').html('');
		} else {
			$('#label_price').html(lang.incorrect);
			error.push('price');
		}
	}
	
	if ($('#title').val() == '') {
		$('#label_title').html(lang.must_be_not_empty);
		error.push('header');
	} else {
		if (   (($('#title').val()[0].charCodeAt(0) > 64) && ($('#title').val()[0].charCodeAt(0) < 91))
			|| (($('#title').val()[0].charCodeAt(0) > 1039) && ($('#title').val()[0].charCodeAt(0) < 1072))
			||   $('#title').val()[0].charCodeAt(0) == 1028
			||   $('#title').val()[0].charCodeAt(0) == 1030
			||   $('#title').val()[0].charCodeAt(0) == 1031) {
			$('#label_title').html('');
		} else {
			$('#label_title').html(lang.incorrect);
			error.push('header');
		}
	}
	
	if ($('#body').val() == '') {
		$('#label_body').html(lang.must_be_not_empty);
		error.push('description');
	} else {
		$('#label_body').html('');
	}
	
	if (error.length > 0) {
		var error_msg = "Допущено ошибку в следующих полях: \n";
		for(var field in error) {
			error_msg += "\t" + lang[error[field]] + "\n";
			
		}
		alert(error_msg);
		error = true;
		$('#advert_files').val('');
	} else {
		error = false;
	}
	if (update == 'update') {
		$('#advert_create').attr('action', 'advert/update');
	}
	
	return !error;
}

function http_delete_image(image_key, image_location) {
	jQuery.post(
		'advert/delete_image',
		'image_src=' + image_key + '&image_location=' + image_location,
		function(data)
		{
			if (image_location == 'cache') {
				$('#image_input_' + image_key + '_small').remove();
				$('#image_input_' + image_key + '_medium').remove();
				$('#image_input_' + image_key + '_large').remove();
				upload_photo_previev();
			} else {
				upload_photo_previev(1);
			}
		}
	);
}

function upload_photo_previev (url) {
	var advert_create = document.getElementById('advert_create');
	if (advert_create) {
		if (url) {
			$('#advert_create').attr('action', location.pathname);
			$('#advert_create').attr('onsubmit', 'return validate_advert_create_form(\'edit\')');
			$('#advert_create').submit();
		} else {
			$('#advert_create').attr('action', 'advert/create#files');
			$('#advert_create').submit();
		}
	}
}
function submit_advert_create () {
	var speed_search = document.getElementById('speed_search');
	if (speed_search) {
		$('#speed_search').attr('action', 'advert/create').submit();
	} else {
		window.location = 'advert/create';
	}
}

function set_session_location (location_id) {
	jQuery.ajax({
		type: 'POST',
		url: base + 'adverts/set_session_location',
		data: 'location_id=' + location_id,
		success: function(){
			location.reload();
		},
		dataType: 'json'
	});
}

function show_response_form (id) {
	$('#response_button_' + id).hide(15, function(){
		$('#response_form_' + id).slideDown(300);
	});
}

function send_response (id) {
	$('#please_wait').fadeIn(150);
	$('#response_form_' + id).slideUp(300, function(){
		jQuery.ajax({
			type: 'POST',
			url: base + 'advert/send_response',
			data: $('#response_form_' + id).serialize(),
			success: function(data){
				if(data) {
					$('#label_response_form_' + id).html('Ваше письмо отправлено!');
					$('#please_wait').fadeOut(150);
				} else {
					$('#label_response_form_' + id).html('Ошибка отправки сообщения').css('color', 'red');
					$('#please_wait').fadeOut(150);
				}
			},
			error: function(){
				$('#label_response_form_' + id).html('Ошибка отправки сообщения').css('color', 'red');
				$('#please_wait').fadeOut(150);
			},
			dataType: 'json'
		});
		
	});
}

function send_abuse(id) {
	$('#please_wait').fadeIn(150);
	$('#abuse_button_' + id).hide(15);
	jQuery.ajax({
		type: 'POST',
		url: base + 'advert/send_abuse',
		data: 'abuse_advert_id=' + id,
		success: function(){
			$('#label_abuse_' + id).html('Ваша жалоба отправлена модератору доски объявлений. Спасибо.');
			$('#please_wait').fadeOut(150);
		},
		error: function(){
			$('#label_abuse_' + id).html('Ошибка отправки сообщения').css('color', 'red');
			$('#please_wait').fadeOut(150);
		},
		dataType: 'json'
	});
}

function get_substructure(parent_id, substructure) {
	if ($('#select_folder0').val() == 0 || parent_id == 0){
		$('#select_folder1').hide();
	} else {
		$('#select_folder1').show();
		$('#please_wait').fadeIn(150);
		$('#select_folder1').html('');
		jQuery.ajax({
			type: 'POST',
			url: base + 'adverts/get_http_substructure',
			data: 'parent_id=' + parent_id + '&substructure=' + substructure,
			success: function(response){
				$('#select_folder1').html(response);
			},
			dataType: 'json'
		});
		$('#please_wait').fadeOut(150);
	}
}

function slideDown_slideUp(object, interval) {
	if (object.css('display') == '' || object.css('display') == 'block'){
		object.slideUp(interval);
	} else {
		object.slideDown(interval);
	}
}

function get_locations () {
	var city_list = $('#city_list');
	if (city_list.html()) {
		slideDown_slideUp(city_list, 100)
	} else {
		$('#please_wait').fadeIn(150);
		jQuery.ajax({
			type: 'POST',
			url: base + 'adverts/get_http_locations',
			success: function(response){
				city_list.html(response).css('display', 'none');
				city_list.slideDown(100);
			},
			dataType: 'json'
		});
		$('#please_wait').fadeOut(150);
	}
}

function sort_by(id, prev) {
	var sort_by = '';
	if (prev == id) {
		$('#sort_by').val(id + '_d');
	} else {
		$('#sort_by').val(id);
	}
	$('#speed_search').submit();
}

function get_advert_content (id) {
	var content = $('#advert_content_' + id);
	if (content.html()) {
		slideDown_slideUp(content, 200)
	} else {
		$('#please_wait').fadeIn(150);
		jQuery.ajax({
			type: 'POST',
			url: base + 'adverts/get_http_advert',
			data: 'advert_id=' + id,
			success: function(advert){
				$('#advert_content_' + id).html(advert).css({padding: '10px', display: 'none'});
				$('#advert_content_' + id).slideDown(200);
				$('#please_wait').fadeOut(150);
			},
			dataType: 'json'
		});
	}
}

function show_hide_element(id) {
	if ($('#select_folder0').val() == 0){
		$('#select_folder1').hide();
	}
	var content = document.getElementById(id);
	if (content.style.display == '' || content.style.display == 'block') {
		$('#' + id).slideUp(200);
	} else if (content.style.display == 'none') {
		$('#' + id).slideDown(200);
	}
}

function set_select_element(select_id, val) {
	$('#' + select_id).val(val);
}

function change_search_criteria(action) {
	$('#speed_search').attr('action', action);
	$('#speed_search').submit();
}

function bookmark(title, url) {
	if (title == undefined){
		title = document.title;
	}
	if (url == undefined){
		url = top.location.href;
	}
	if (window.sidebar) {
		window.sidebar.addPanel(title, url, '');
	} else if (window.opera && window.print) {
		t.setAttribute('rel', 'sidebar');
		t.setAttribute('href', url);
		t.setAttribute('title', title);
		t.click();
	} else {
		window.external.AddFavorite(url, title);
	}
}
