//THIS BIT OF CODE WILL ALWAYS RUN INT THE INTIRE WEBSITE
//INSERT ALL YOU WANT TO BE RUN
$(document).ready(function(){ 
	//START: creates html5 placeholder illusion
	$('[placeholder]').focus(function() {
		var input = $(this);
		if (input.val() == input.attr('placeholder')) {
			input.val('');
			input.removeClass('placeholder');
		}
	}).blur(function() {
		var input = $(this);
		if (input.val() == '' || input.val() == input.attr('placeholder')) {
			input.addClass('placeholder');
			input.val(input.attr('placeholder'));
		}
	}).blur();
	//prevents input from being submited with placeholder value
	$('[placeholder]').parents('form').submit(function() {
		$(this).find('[placeholder]').each(function() {
			var input = $(this);
			if (input.val() == input.attr('placeholder')) {
				input.val('');
			}
		})
	});
	//START: creates html5 placeholder illusion
});

function autoviva_round_corners(){

}

function own_rating(label, type, ref, vote_value, owner){

        //LOAD TRANSLATION
        if (typeof labels == "undefined"){
            $.getScript('/js_translate_rating.php', function(){});
        }

        var labels_index = 5;
        switch(type)
        {
            case "passion":
              labels_index = 0;
              break;
            case "reliability":
              labels_index = 1;
              break;
            case "efficiency":
              labels_index = 2;
              break;
            case "praticality":
              labels_index = 3;
              break;
            case "fun":
              labels_index = 4;
              break;
            default:
              labels_index = 5;
        }

	$(function(){
		$('#heat_rate_'+type).rating_mv(label, 5, vote_value, owner, labels[labels_index]).bind('ratingchanged',
		function(event, data) {
			$.get("/ax_rate_mycar.php", {ref_id:ref, vote:data.rating, type:type});
		     return false;
		});
	});
}


function percentil_stats(label, perc, value, units, id){
	if(id==null || id=='') id=label;
	$(function(){
		$('#percentil_'+id).percentil_mv(label, perc, value, units);
	});
}

var feeds_page_count = 0;
function hp_more_feeds_list(tab, type, extra_id, search_str,grid_layout,show_first,type_id, filters){
	if(grid_layout) send_grid_layout=1;
	else send_grid_layout=0;

	if(search_str==null) search_str="";
	if($('#inmember').length){
		feeds_more_old=$("#feeds_more").html();
		$("#feeds_more").remove();
		feeds_old=$("#feeds_list").html();
	}
	$("#feeds_list").append('<div id="loader">'+img_loader(24)+'</div>');
	if(!show_first) feeds_page_count++;
	$.get("/ax_feeds_hp_more.php", {feeds_page_count: feeds_page_count, tab:tab, type:type, extra_id: extra_id, search_str: search_str,grid_layout:send_grid_layout,type_id:type_id,filters:filters},
		function(data){
			if($('#inmember').length){
				new_feeds_more = '<div id="feeds_more">'+feeds_more_old+'</div>';
				$("#feeds_list").html(feeds_old+data+new_feeds_more);
			}else{
				$("#feeds_list").append(data);
			}
			$('#loader').remove();
			realTimeAdjustment();
			setMouseOvers();
	});
}


function community_feeds_list(tab, type, extra_id, classe, selected, search_str, feeds_page_count){
	if(search_str==null) search_str="";

	send_grid_layout=0;
	$('#feeds_more').remove();
	var old_html = '';
	if(!feeds_page_count) feeds_page_count = 0;

	if($("#feeds_list").length) old_html = $("#feeds_list").html();
	
	if(!feeds_page_count){	
		$("#feeds_list").append('<div id="lcontent'+feeds_page_count+'"></div>');		
	}else{
		$("#lcontent"+(feeds_page_count-1)).append('<div id="lcontent'+feeds_page_count+'"></div>');
	}	
	
	$("#lcontent"+feeds_page_count).html("<center>"+img_loader(17)+"</center>");
	
	$.get("/ax_feeds_hp_more.php", {feeds_page_count: feeds_page_count, tab:tab, type:type, extra_id: extra_id, search_str: search_str,grid_layout:send_grid_layout, search_str: search_str, allow_comments: 0},
		function(data){
			$("#lcontent"+feeds_page_count).html(data);
	});
	switch(selected){
		case '0':
			$('.selected_arrow').css('margin-left','8px');
		break;

		case '1':
			$('.selected_arrow').css('margin-left','104px');
		break;

		case '2':
			$('.selected_arrow').css('margin-left','200px');
		break;
	}
	$('[id^="'+classe+'"]').removeClass();
	$('#'+classe+selected).addClass('on');
	
	//if(feeds_page_count>0) setTimeout('scrollToFooter()', 500);
	console.log(search_str);
}

function scrollToFooter(){
	$(document).scrollTo($('.footer'), 100);
}



function like_unlike(reftype,refid)
{
	var $like_placeholder = $("#like_placeholder");
	$like_placeholder.fadeOut('fast');
	$.get("/ax_like_unlike.php", {reftype:reftype,refid:refid},
		function(data){
			$like_placeholder.html(data)
					 .fadeIn('fast');
		});
}

function like_unlike_featuredarticle(article_id)
{
	var $like_placeholder = $("#like_placeholder");
	$like_placeholder.fadeOut('fast',function(){
		$.get("/ax_fan_featuredarticle.php", {article_id: article_id},
			function(data){
				$like_placeholder.html(data)
						 .fadeIn('fast');
			});
	});
}


function like_unlike_dreamgarage(dreamgarage_id)
{
	$.get("/ax_fan_dreamgarage.php", {dreamgarage_id: dreamgarage_id},
		function(data){
			if(data==1){
				$(".white_item_bg_like").addClass("white_item_bg_like_sel");
				$(".white_item_bg_like").removeClass("white_item_bg_like");
			}else{
				$(".white_item_bg_like_sel").addClass("white_item_bg_like");
				$(".white_item_bg_like_sel").removeClass("white_item_bg_like_sel");
			}
		}
	);
}

function like_unlike_video(video_id)
{
	$.get("/ax_fan_video.php", {video_id: video_id},
		function(data){
			if(data==1){
				$(".white_item_bg_like").addClass("white_item_bg_like_sel")
							.removeClass("white_item_bg_like");
			}else{
				$(".white_item_bg_like_sel").addClass("white_item_bg_like")
							    .removeClass("white_item_bg_like_sel");
			}
		}
	);
}

function like_unlike_news(news_id)
{
	var $like_placeholder = $("#like_placeholder");
	$like_placeholder.fadeOut('fast',function(){
		$.get("/ax_fan_news.php", {news_id: news_id},
			function(data){
				$like_placeholder.html(data);
				$like_placeholder.fadeIn('fast');
				if(data.indexOf('news_tools_selected')!=-1){
					$('.likes_darkgrey').html($('.likes_darkgrey').html()*1+1);
				}
			});
	});
}

function like_unlike_post(post_id)
{
	$.get("/ax_fan_post.php", {post_id: post_id},
		function(data){
			if(data==1){
				$(".white_item_bg_like").addClass("white_item_bg_like_sel")
							.removeClass("white_item_bg_like");
			}else{
				$(".white_item_bg_like_sel").addClass("white_item_bg_like")
							    .removeClass("white_item_bg_like_sel");
			}
		});
}

function like_unlike_photo(photo_id,element)
{
	$.get("/ax_fan_photo.php", {photo_id: photo_id,element: element},
		function(data){
			if(data==1){
				$(".white_item_bg_like").addClass("white_item_bg_like_sel")
							.removeClass("white_item_bg_like");
			}else{
				$(".white_item_bg_like_sel").addClass("white_item_bg_like")
							    .removeClass("white_item_bg_like_sel");
			}
		}
	);
}

function open_search_pane(){
	$("#result_options_closed").hide();
	$("#result_options_open").show();
}
function close_search_pane(){
	$("#result_options_open").hide();
	$("#result_options_closed").show();
}

var lastActiveUserShown = 1;
function showActiveUserInfo(un){
	$('#active_user_info_'+lastActiveUserShown).hide();
	$('#active_user_pic_'+lastActiveUserShown).css('border-color','transparent');

	$('#active_user_info_'+un).show();
	$('#active_user_pic_'+un).css('border-color','#FFF');

	lastActiveUserShown = un;
}

/*START********************** NOTIFY  MENU ***********************/
var notifyCloseTimer;
var notifyOpen = false;
function showNotifyMenu(){
	hideUserMenu();
	if(notifyOpen==false){
		$.get("/ax_notify_menu.php", null,
			function(data){
				var $notify_menu = $("#notify_menu");
				$notify_menu.html(data);
				$notify_menu.mouseleave(function(){
					notifyCloseTimer = window.setInterval(function() {
						hideNotifyMenu();
					}, 250);
				});

				$notify_menu.mouseenter(function(){
					clearInterval(notifyCloseTimer);
				});
			}
		);
		notifyOpen = true;
	}else{
		hideNotifyMenu();
	}
}

function hideNotifyMenu(){
	clearInterval(notifyCloseTimer);
	$("#notify_menu").unbind('mouseenter mouseleave')
			 .html('');
	notifyOpen = false;
}
/*END********************** NOTIFY  MENU ***********************/

/*START********************** USER  MENU ***********************/
var userMenuCloseTimer;
var userMenuOpen = false;
function showUserMenu(){
	hideNotifyMenu();
	if(userMenuOpen==false){
		var $usermenu = $('#usermenu');
		$usermenu.show();
		$usermenu.mouseleave(function(){
			userMenuCloseTimer = window.setInterval(function() {
				hideUserMenu();
			}, 250);
		});

		$usermenu.mouseenter(function(){
			clearInterval(userMenuCloseTimer);
		});
		userMenuOpen = true;
	}else{
		hideUserMenu();
	}
}

function hideUserMenu(){
	clearInterval(userMenuCloseTimer);
	$("#usermenu").unbind('mouseenter mouseleave')
		      .hide();
	userMenuOpen = false;
}
/*END********************** USER  MENU ***********************/

function closeStartBanner(username){
	$.get("/ax_set_start_banner_seen.php", {username: username},
			function(data){
				if(data=='ok'){
					$('#start_banner').remove();
				}
			}
		);
}

function welcomeCheckAll(){
	$('input[id^="check_"]').attr('checked',$('#checker').attr('checked'));
}

function resendConfirmation(labels){
	if (typeof(labels) == "undefined"){
			labels = new Array('An email has been sent. Please confirm your email address!','an unknow error has occurred');
	}
	
	var old_html;
	old_html = $('#resend_response').html();
	$('#resend_response').fadeOut('fast',function(){
		$('#resend_response').html(img_loader(14)).fadeIn('slow');
	});
	$.get("/ax_resend_confirmation.php", null,
		function(data){
			if(data=='ok'){
				$('#resend_response').fadeOut('slow',function(){
					$('#resend_response').html(labels[0]).fadeIn('slow',function(){
						var pause = function() {
							$('#resend_response').fadeOut('slow',function(){
								$('#resend_response').html(old_html).fadeIn('slow');
							});
						};
						setTimeout(pause,10000);
					});
				});
			}else{
				$('#resend_response').html(labels[1]);
			}
		}
	);
}

var logginCountDown;
function startLogginCounter(){
	logginCountDown = parseInt($('#counter').html());
	setInterval(function(){
		logginCountDown = logginCountDown - 1;
		$('#counter').html(logginCountDown);
		if(logginCountDown==0) document.location.href="/welcome.php";
	}, 1000);
}

function get_ads_uploaded_photos(objid,acode){
	$.get("/ax_get_temp_uploaded_photos.php", {scode: acode},
		function(data){
			$('#'+objid).html(data);
		}
	);
}

var oldId='';
function setMainUploadedImage(id){
	$.ajax({
		type: "GET",
		url: "ax_uploaded_image_setmain.php",
		data: "id=" + id+"&oldId=" + oldId,
		success: function(msg){
			if(msg=='success'){
				$('.mainUploadedImage').removeClass('mainUploadedImage');

				$("div[id^='uploadedImage']").css('background-color','#F2F2F2');
				$("div[id^='uploadedImage']").css('border','2px solid #F2F2F2');
				$("img[class^='removeUploadedImage']").hide();

				$('#uploadedImage'+id).css('background-color','#09C')
						      .css('border','2px solid #09C');
				$('.removeUploadedImage'+id).show();

				oldId = id;
			}else{
				autoviva_alert(msg);
			}
		}
	});
}

function removeUploadedImage(id){
	$.ajax({
		type: "GET",
		url: "ax_uploaded_image_remove.php",
		data: "id=" + id,
		success: function(msg){
			if(msg=='success'){
				$('#uploadedImage'+id).fadeOut(200,function(){
					$(this).remove();
				});
			}else{
				autoviva_alert(msg);
			}
		}
	});
}

function validate_welcome_add_buddies(labels){
	if (typeof(labels) == "undefined"){
			labels = new Array('Please select at least one contact');
	}
	
	var one_is_selected = 0;
	$.each($('input[type=checkbox]'),function(){
		if($(this).attr('checked')) one_is_selected++;
	});
	if(one_is_selected==0) autoviva_alert(labels[0]);
	else $('#form_welcome_add_buddies').submit();
}

function validate_welcome_invite(labels){
	if (typeof(labels) == "undefined"){
			labels = new Array('Please select at least one contact');
	}
	var one_is_selected = 0;
	$.each($('input[type=checkbox]'),function(){
		if($(this).attr('checked')) one_is_selected++;
	});
	if(one_is_selected==0) autoviva_alert(labels[0]);
	else $('#form_welcome_invite').submit();
}

function validate_advanced_addcar(labels){
	if (typeof(labels) == "undefined"){
			labels = new Array('Please select a car');
	}
	if($('#addcar_version').val()!=0) return true;
	else autoviva_alert(labels[0]);
	return false;
}

function validate_basic_addcar(){
	if (typeof(labels) == "undefined"){
			labels = new Array('Please select a car');
	}
	if($('#ncar_model').val()!=0) return true;
	else autoviva_alert(labels[0]);
	return false;
}

var total_to_load = 0;
function setAutoloader(classname,func){
	total_to_load = $('.'+classname).length;
	$('.'+classname).load(function(){
		total_to_load--;
		if(total_to_load==1){
			if(func) func();
			else  adjustImageToFrame();
		}
	});
}



function change_photo_event(name, path, img_path, img_width, img_height, licence_txt, titlealt){
	if(document.images[name].src.indexOf(path+img_path)==-1){
		if(licence_txt==null)licence_txt="";
		loadImage('event_photo_profile',path+img_path);
		$("#licence_photo").html(licence_txt);
		$('#event_photo_profile').attr('title',titlealt); //NEWS
		$('#event_photo_profile').attr('alt',titlealt); //NEWS
	}
}

var preloaded_images = new Array();
function preload_image(image_url){
	// Image already loaded, should be in cache
	if(preloaded_images[image_url])
		return;

	var img = new Image();
	img.src = image_url;
	img.onload = function(){
		preloaded_images[image_url] = 1;
	}
}

function preload_next_image(){
	if(typeof( actualPhotoCounter ) != 'undefined' && typeof( carPhotos ) != 'undefined'){
		var next = actualPhotoCounter+1;
		if(next > maxPhotoCounter){
			next = 0;
		}
		preload_image(carPhotos[next]);
	}
}

$(document).ready(function(){
	preload_next_image();
});

function loadImage(img_id, new_img_src){
	
	//get the parent element reference
	var parent_element = $('#'+img_id).parent();

	//remove any loaders that may exist inside the parent container
	parent_element.children('#img_loader').remove();

	if(typeof( carPhotosCompensate ) != 'undefined'){
		$('#'+img_id).attr('rel',carPhotosCompensate[actualPhotoCounter]); //NEWS
	}
	
	var $current_img = $('#'+img_id);
	var $next_img	 = $current_img.clone();
	
	/*
	$next_img.attr('data-width', $current_img.width());
	$next_img.attr('data-height', $current_img.height());
	*/
	
	//add and style loader to parent element
	var loader_size = 48;
	var $img_loader = $(img_loader(loader_size));
	$img_loader.css({
		'position'	: 'absolute',
		'left'		: '50%',
		'marginLeft'	: '-'+(loader_size/2)+'px',
		'width'		: loader_size+'px',
		'top'		: '50%',
		'marginTop'	: '-'+(loader_size/2)+'px',
		'height'	: loader_size+'px',
		zIndex		: 2
	});
	var default_position = parent_element.css('position');
	parent_element.css('position', 'relative').prepend($img_loader);


	// We must bind the load event before changing src: IE8 problem
	$next_img.load( function(){
		$current_img.replaceWith($next_img);
		parent_element.children('#img_loader').remove();
		parent_element.css('position', default_position);
		
		$next_img.fadeTo(0, 0.6)
			 .fadeTo(100, 1);
		
		adjustImageToFrame();
	});
	
	$next_img.attr('src', new_img_src);
	
	preload_next_image();
	return false;
}

function loadImage_OLD(img_id,new_img_src){
	
	var carPhotosCompensate;
	//get the parent element reference
	var parent_element = $('#'+img_id).parent();

	//remove any loaders that may exist inside the parent container
	parent_element.children('#img_loader').remove();

	if(typeof( carPhotosCompensate ) != 'undefined'){
		$('#'+img_id).attr('rel',carPhotosCompensate[actualPhotoCounter]); //NEWS
	}
	
	//on load remove loader
	$('#'+img_id).load(function(){
		adjustImageToFrame();
		$('#'+img_id).fadeIn(200,function(){
			parent_element.children('#img_loader').remove();
		});
	});

	//fade out current image
	$('#'+img_id).fadeOut(200,function(){

		//add and style loader to parent element
		var loader_size = 48;
		parent_element.prepend(img_loader(loader_size));
		$('#img_loader').css('position','relative');
		$('#img_loader').css('left','50%');
		$('#img_loader').css('margin-left','-'+(loader_size/2)+'px');
		$('#img_loader').css('width',loader_size+'px');
		$('#img_loader').css('top','50%');
		$('#img_loader').css('margin-top','-'+(loader_size/2)+'px');
		$('#img_loader').css('height',loader_size+'px');




		//start loading the new image
		$('#'+img_id).attr('src',new_img_src);
	});

	return false; //render any other html related events (like href) obsolete
}

function rotateAndAdjustPhotos(where_to,img_id){
	var titleAltPhotos;
	if(where_to=='forward'){
		if(actualPhotoCounter>=maxPhotoCounter){
			actualPhotoCounter=0;
		}else{
			actualPhotoCounter++;
		}
	}else{
		if(actualPhotoCounter>0){
			actualPhotoCounter--;
		}else{
			actualPhotoCounter=maxPhotoCounter;
		}
	}
	

	if(img_id){
		if(typeof( carPhotosCompensate ) != 'undefined'){
			$('#'+img_id).attr('rel', carPhotosCompensate[actualPhotoCounter]);	
		}
		loadImage(img_id,carPhotos[actualPhotoCounter]);
	}else{
		if(typeof( carPhotosCompensate ) != 'undefined'){
			$('.imageautoadjust').attr('rel', carPhotosCompensate[actualPhotoCounter]);	
		}
		$('.imageautoadjust').attr('src',carPhotos[actualPhotoCounter]);
	}

	$('#licence_photo2').html(licencePhotos[actualPhotoCounter]); //NEWS
	if(typeof( titleAltPhotos ) != 'undefined'){
		$('#licence_photo').html(licencePhotos[actualPhotoCounter]); //NEWS
		$('#news_photo_profile').attr('title',titleAltPhotos[actualPhotoCounter]); //NEWS
		$('#news_photo_profile').attr('alt',titleAltPhotos[actualPhotoCounter]); //NEWS
	}
}

function change_photo(name, path, img_path, img_width, img_height, licence_txt, titlealt){
	var carPhotosCompensate;
	if(document.images[name].src.indexOf(path+img_path)==-1){
		if(typeof( carPhotosCompensate ) != 'undefined'){
			for(i=0;i<carPhotos.length;i++){
				if(carPhotos[i]==path+img_path){
					actualPhotoCounter = i;
				}
			}
		}
		if(licence_txt==null)licence_txt = "";
		loadImage('news_photo_profile',path+img_path);
		$("#licence_photo").html(licence_txt);
		$('#news_photo_profile').attr('title',titlealt).attr('alt',titlealt); //NEWS
	}
}

function compensate_pic(where){
	var $img		= $('.imageautoadjust');
	var current_comp	= parseInt($img.attr('rel'));
	if(isNaN(current_comp)){
		current_comp = 0;
	}

	// already at maximun type, there is no need of another http request
	if( (current_comp <= -2 && where == 'down') || (current_comp >= 2 && where == 'up') ){
		return;
	}

	$.ajax({
		type: "GET",
		url: "/ax_compensate_photo.php",
		data: "id=" + carPhotosIds[actualPhotoCounter] + "&direction=" + where,
		success: function(msg){
			carPhotosCompensate[actualPhotoCounter] = msg;

			$img.attr('rel', msg);
			adjustImageToFrame();
		}
	});
	
	/*
	// Old code -> compensation based on pxs
	$.ajax({
		type: "GET",
		url: "/ax_compensate_photo.php",
		data: "id=" + carPhotosIds[actualPhotoCounter] + "&direction=" + where,
		success: function(msg){
			carPhotosCompensate[actualPhotoCounter] = msg;
			if(where=='up'){
				$('.imageautoadjust').css('margin-top', parseInt($('.imageautoadjust').css('margin-top'))-10);
			}else{
				$('.imageautoadjust').css('margin-top', parseInt($('.imageautoadjust').css('margin-top'))+10);
			}
		}
	});
	*/
}

function enc_select_image(img_id,new_img_src,thumb_id, info_index){
	loadImage(img_id,new_img_src);

	$('.thumb_selected').addClass('thumb')
			    .removeClass('thumb_selected');

	$('#'+thumb_id).addClass('thumb_selected')
		       .removeClass('thumb');

	$('#makemodelc').html(makeversion[info_index]);


	$('#bigimghref').attr('title', makeversion[info_index]);
	$('#bigimg').attr('alt', makeversion[info_index]);

	try{
		$('#datesc').html(dates[info_index]);
	}catch(e){}
	$('#statsc').html(stats[info_index]);
	$('#link').click(function(){
		document.location.href="/version.php?id="+versions[info_index]+"&sec=profile";
	});

	return false;
}

function sendAdvertiserEmail(id,is_logged){
	var name = $("#ctc_name").val();
	var email = $("#ctc_email").val();
	var phone = $("#ctc_phone").val();
	var msg = $("#ctc_msg").val();
	var captcha="";
	if(is_logged==1) captcha = $("#ctc_captcha").val();
	$.ajax({
		type: "GET",
		url: "/ax_ads_review.php",
		data: "id=" + id + "&ctc_msg="+msg + "&ctc_name="+name + "&ctc_email="+email + "&ctc_phone="+phone + "&ctc_captcha="+captcha,
		success: function(msg){
			parts = msg.split('@@code@@');
			if(parts[0]=='success'){
				autoviva_alert(parts[1],true);
			}else if(parts[0]=='error' || parts[0]=='warn'){
				autoviva_alert(parts[1]);
			}
		}
	});
}

function mng_set_main_photo(id, labels){
	if (typeof(labels) == "undefined"){
			labels = new Array('An error occured while setting main photo. Please try again.');
	}
	
	$.ajax({
		type: "GET",
		url: "/ax_mng_set_main_photo.php",
		data: "id=" + id,
		success: function(msg){
			if(msg=='ok'){
				$('.main').removeClass('main');
				$('#cp'+id).addClass('main');
				$("span[id^='cpmain']").remove();
				$('#cp'+id).append('<span style="font:bold 12px Helvetica; color:#FFF" id="cpmain'+id+'">main</span>');
			}else{
				autoviva_alert(labels[0]);
			}
		}
	});
}

function mng_check_checked_photos(){
	var count = 0;
	$("input[id^='checked_photo']").each(function(){
		if($(this).attr('checked')) count++;
	});
	if(count>0){
		$('#btn_del_photos').removeClass('acc_button_disabled')
				    .addClass('acc_button');
	}else{
		$('#btn_del_photos').removeClass('acc_button')
				    .addClass('acc_button_disabled');
	}
}

function get_mng_uploaded_photos(ads_id){
	$.get("/ax_mng_get_uploaded_photos.php", {ads_id: ads_id},
		function(data){
			$('#photo_container').html(data);
		}
	);
}

function mng_select_video(id){
	if($('#checked_video'+id).attr('checked')) $('#checked_video'+id).attr('checked',false);
	else $('#checked_video'+id).attr('checked',true);
	mng_check_checked_videos();
}

function mng_check_checked_videos(){
	var count = 0;
	$("input[id^='checked_video']").each(function(){
		if($(this).attr('checked')) count++;
	});
	if(count>0){
		$('#btn_del_videos').removeClass('acc_button_disabled').addClass('acc_button');
	}else{
		$('#btn_del_videos').removeClass('acc_button').addClass('acc_button_disabled');
	}
}

function popin_edit_photo_encyclopedia(id){
	createAndShowPopin('ax_popin_id_this_car.php?photo_id='+id,'','');
}

function popin_edit_video_encyclopedia(id){
	createAndShowPopin('ax_popin_id_this_car.php?video_id='+id,'',''); 
}

function update_photo_title(id,title, labels){
	if (typeof(labels) == "undefined"){
			labels = new Array('An error occured while updating your photo\'s title. Please try again.');
	}
	
	$.ajax({
		type: "GET",
		url: "/ax_update_photo_title.php",
		data: "id=" + id + "&title=" + title,
		success: function(msg){
			if(msg=='ok'){
				destroyAndRemovePopin();
				$("#photo_title_id").html(title);
			}else{
				autoviva_alert(labels[0]);
			}
		}
	});
}

function update_video_title(id,title, labels){
	if (typeof(labels) == "undefined"){
			labels = new Array('An error occured while updating your video\'s title. Please try again.');
	}
	$.ajax({
		type: "GET",
		url: "/ax_update_video_title.php",
		data: "id=" + id + "&title=" + title,
		success: function(msg){
			if(msg=='ok'){
				destroyAndRemovePopin();
				$("#video_title_id").html(title);
			}else{
				autoviva_alert(labels[0]);
			}
		}
	});
}

function loadSuperpostImage(img_id,new_img_src){
	var p = $('#'+img_id);
	var p_parent = p.parents('div').eq(0);

	if(p.attr('src')!=new_img_src){
		//fix photo space height
		p_parent.height(p.height());
		//hide photo
		p.fadeOut(75, function(){
			//load new photo
			p.attr('src',new_img_src);
			//resize photo space height
			p.load(function(){
				p_parent.animate({
					height:p.height()+'px'
				}, 75,function(){
					p.fadeIn(75);		
				});
			});
		});
	}
}

function load_multimedia(path_html, type, current){
	//select thumbnail
	$('.thumb').css('border','2px solid #666');
	$('#'+current).css('border','2px solid #fff');

	if(type=='img'){
		$('#vholder').hide();
		loadSuperpostImage('floader',path_html);
		$('#fholder').show();

	}else{
		$('#fholder').hide();
		$('#vloader').html(path_html);
		$('#vholder').show();
	}
}

var thumbnail_page = 0;
function more_thumbnails(direction, post_id, maximum_pages){
	if(direction=='left' && thumbnail_page>0) thumbnail_page--;
	if(direction=='right' && thumbnail_page<maximum_pages) thumbnail_page++;
	$("#thumb_holder").fadeOut('slow',function(){
		$.ajax({
			type: "GET",
			url: "/ax_navigate_post_thumbs.php",
			data: "id=" + post_id + "&page=" + thumbnail_page,
			success: function(msg){
				check_thumbnail_navigation(maximum_pages);
				$("#thumb_holder").html(msg).fadeIn('slow');
			}
		});
	});
}

function slide_left_superpost_thumbs(){
	var diff = $("#thumb_roller").width()-$("#thumb_holder").width();
	var actual_value = parseInt($("#thumb_roller").css('margin-left'));
	if(diff>Math.abs(actual_value)){
		actual_value -= $("#thumb_holder").width()/2;
		if(Math.abs(actual_value)>diff) actual_value = -diff;
		$("#thumb_roller").animate({
			marginLeft: actual_value+'px'
		}, 500);
	}
}


function slide_right_superpost_thumbs(){
	var actual_value = parseInt($("#thumb_roller").css('margin-left'));
	if(actual_value<0){
		actual_value += $("#thumb_holder").width()/2;
		if(actual_value>0) actual_value = 0;
		$("#thumb_roller").animate({
			marginLeft: actual_value+'px'
		}, 500);
	}
}


function check_thumbnail_navigation(maximum_pages){
	if(thumbnail_page>0){
		$('.left').show();

	}else{
		$('.left').hide();
	}

	if(thumbnail_page<maximum_pages){
		$('.right').show();
	}else{
		$('.right').hide();
	}
}

function launchUntrustedLink(o,ref,ref_id){
	o.attr('target','_blank');
	o.attr('href','/launch.php?url='+o.attr('href')+'&ref='+ref+'&ref_id='+ref_id);
}

function launch_notification_link(nid){
	$.ajax({
		type: "GET",
		url: "/ax_delete_notification.php",
		data: "nid=" + nid,
		success: function(lnk){
			document.location.href=lnk;
		}
	});
}

function open_close_search_pane(o, labels){
	if (typeof(labels) == "undefined"){
			labels = new Array('show options','hide options');
	}
	
	if(o.html()==labels[0]){
		o.html(labels[1]);
		open_search_pane();
	}else{
		o.html(labels[0]);
		close_search_pane();
	}
}

function send_news_comment(cid){
	var comment = jQuery.trim($('#comm_msg_'+cid).val());
	if(comment!=''){
		if(cid){
			$.get("/ax_send_news_comment.php", {cid: cid, msg: comment},
				function(data){
					$('.news_leftbar').append(data);
					$('#form_comm_post_'+cid).remove();
					$('.post_comment.').remove();
				}
			);
		}
	}else{
		$('#errorcom_'+cid).show();
		$('#errorcom_'+cid).fadeOut(1000);
	}
}

$(document).ready(function(){
	$('.small_edit').mouseenter(function(){
		$(this).children().each(function() {
			var nclass = $(this).attr('class');
			$(this).addClass(nclass+'_over');
			$(this).removeClass(nclass);
		});
	});

	$('.small_edit').mouseleave(function(){
		$(this).children().each(function() {
			var nclass = $(this).attr('class');
			$(this).removeClass(nclass);
			$(this).addClass(nclass.replace('_over',''));
		});
	});

	$('.small_edit_normal').mouseenter(function(){
		$(this).children().each(function() {
			var nclass = $(this).attr('class');
			$(this).addClass(nclass+'_over');
			$(this).removeClass(nclass);
		});
	});

	$('.small_edit_normal').mouseleave(function(){
		$(this).children().each(function() {
			var nclass = $(this).attr('class');
			$(this).removeClass(nclass);
			$(this).addClass(nclass.replace('_over',''));
		});
	});
});

function wiki_additional_remarks(type){
	if(type=='open'){
		$('.remarks_button').hide();
		$('.remarks').show();
	}else{
		$('.remarks_button').show();
		$('.remarks').hide();
	}
}

function show_hidden_comment(id){
	$('#hide_comm_'+id).show();
	$('#show_comm_'+id).hide();
}

function set_search_buddies_on(){
	var clean="";
	$("#search_gift_buddy_userid").autocomplete("/jqs_predict_buddies.php", {
		minChars:1,
		width:260,
		scroll:true,
		matchContains:true,
		delay:50,selectFirst: false
	}).result(function(event, item) {
		 clean=item[0];
		$("#gift_buddy_userid").val(item[1]);
	}); 
}

function show_photo_publisher(){
	$('html, body').animate({scrollTop: $(document).height()}, 'slow', function(){
		$('#photo_publisher').slideDown('fast',function(){
			$('html, body').animate({scrollTop: $(document).height()}, 'slow');
		});
	});
}

function show_video_publisher(){
	$('html, body').animate({scrollTop: $(document).height()}, 'slow', function(){
		$('#video_publisher').slideDown('fast',function(){
			$('html, body').animate({scrollTop: $(document).height()}, 'slow');
		});
	});
}

function toggleStatus() {
    if ($('#delete_accept').is(':checked')) {
        $('[id^="confirm_delete"]').removeAttr('disabled');
	$('[id^="confirm_delete"]').removeClass('button_av2form_disabled');
    } else {
        $('[id^="confirm_delete"]').attr('disabled', true);
	$('[id^="confirm_delete"]').addClass('button_av2form_disabled');
    }   
}

function toggle_specs_edit(option, id)
{
	if(option == 'open')
	{
		$('#show_specs_'+id).hide();
		$('#edit_specs_'+id).show();
	}
	else if('close')
	{
		$('#show_specs_'+id).show();
		$('#edit_specs_'+id).hide();
	}
}

function recover_lost_password(email, labels){
	if (typeof(labels) == "undefined"){
			labels = new Array('checking email...');
	}
	
	$('.error_field').html(img_loader(14) + ' ' + labels[0]);
	$('.error_field').css('color','#333');
	$.post(
		"/ax_popin_send_password.php",
		{
			email: email
		},
		function(data){
			if(data=='success'){
				createAndShowPopin('ax_popin_login.php?ajax=true&recover=true','');
			}else{
				$('.error_field').html(data);
				$('.error_field').css('color','#f00');
			}
		}
	);
	return false;
}

function accept_decline_car_offer(history_id, element_id, accept_decline){
	$('#buttons'+element_id).hide();
	$('#loading'+element_id).html(img_loader(14)).show();
	$.post(
		"/ax_accept_decline_car_offer.php",
		{
			id: history_id,
			op: accept_decline,
			feed_id: element_id
		},
		function(data){
			parts = data.split('@@code@@');
			if(parts[0]=='success'){
				$('#feed_item'+element_id).remove();
				$('#feeds_list_stream').prepend(parts[1]);
				realTimeAdjustment();
			}else{
				if(parts[0]=='clickedtwice'){
					//do nothing
				}else{
					autoviva_alert(parts[1]);
					$('#buttons'+element_id).show();
					$('#loading'+element_id).hide();
				}
			}
		}
	);
}

function show_badge(){
	setTimeout(function() {
		$.get("/ax_get_badge.php",
			function(data){
				if(data!=""){
					$("#notifications .float_left").html(data);
					$("#notifications").show();
					setTimeout(function() {
						$("#notifications").hide();
					}, 12000);
				}
		});
	}, 20000);
}

function update_notify_menu(){
	$.get("/ax_update_notify_menu_count.php", null,
		function(data){
			if(data>0){
				$('.hd_logged .updates').html(data);
			}else{
				$('.hd_logged .updates').remove();
			}
		}
	);
}

function panorama_item_mouseover(pid, ptype){
	var $pid = $('#'+pid).addClass('item_hover').removeClass('item');
	$('#'+pid+' .icon').attr('src','/images/panorama/'+ptype+'_white.png');
	$('#'+pid+' .apostrophe').attr('src','/images/panorama/post_apostrophe_white.png');
	$('#'+pid+' .thumb').show();
	$pid.mouseout(function(){
		$pid.removeClass('item_hover').addClass('item');
		$('#'+pid+' .icon').attr('src','/images/panorama/'+ptype+'.png');
		$('#'+pid+' .apostrophe').attr('src','/images/panorama/post_apostrophe.png');
		$('#'+pid+' .thumb').hide();
	});
}

function isUrl(s) {
	var regexp = /(ftp|http|https):\/\/(\w+:{0,1}\w*@)?(\S+)(:[0-9]+)?(\/|\/([\w#!:.?+=&%@!\-\/]))?/
	return regexp.test(s);
}


function chp_photo(id, img_path, img_width, img_height, img_id){
	document.images["ads_photo"].src = img_path;
	document.images["ads_photo"].width = img_width;
	document.images["ads_photo"].height = img_height;
	
	/*var js = "popin_photo("+img_id+");";
	// create a function from the "js" string
    var newclick = new Function(js);
	
	$('#big_photo_link').attr('onclick', '').click(newclick);
	$('#big_photo_link1').attr('onclick', '').click(newclick);
	
	$.get("/ax_save_views_photo.php", {id: id});*/
}

function calculate_monthly_payments(value, rate, months){
	rate = 1+(rate/100);
	years = months/12;
	total = value*Math.pow(rate,years);
	monthly = Math.round(total/months);
	$.get("/ax_get_formated_price.php", {price:monthly, per:'<span>/month</span>'},
			function(data){
				$('#calc_result').html(data);
			}
		);
}


function show_hide_consumption_interface(){
	if($('#c_fake_interface').css('display')=='none'){
		$('#c_fake_interface').show();
		$('#c_interface').hide();
	}else{
		$('#c_fake_interface').hide();
		$('#c_interface').show();
		$('.c_input').focus();
	}
}

function save_consumption(blank_text, ncars){
	consumption = $("#c_consumption").val();
	if(blank_text!=consumption){
		c_car = $("#consumption_car").val();
		$.getJSON("/ax_save_consumption.php", {consumption_car: c_car, consumption_value: consumption, ncars:ncars},
			function(data){
				if(data.status=="true"){
					$("#feeds_list").prepend(data.message);
					$(".new_feed_item").show("slow");
					$('.left_side span').html(consumption);
					$("#c_consumption").val('');
				}
				show_hide_consumption_interface();
		});
	}
}

function add_to_panorama(pid, labels){
	if (typeof(labels) == "undefined"){
			labels = new Array('not a post');
	}
	
	$.get("/ax_add_to_panorama.php", {post_id:pid},
		function(data){
			if(data=="ok"){
				document.location.href="/";
			}else{
				alert("not a post");
			}
		}
	);
}

function id_this_car(form_id){
	$.get("/ax_id_this_car.php?"+$('#'+form_id).serialize(), null,
		function(data){
			$('#encyclopedia_ajax').html(data);
		}
	);
}

function save_serialized_specs(serialized_specs){
	$.post(
		'/ax_save_serialized_specs.php', 
		serialized_specs,
		function(data) {
			$('.specs_form_id'+data.category)[0].reset();
			$('.specs_form_id'+data.category).hide();
			$('.specs_form_id_save_message'+data.category).show();
			$('.specs_form_id_save_message'+data.category+' td.label h3').html(data.error);
			if(data.success==1){
				
			}else{
				
			}
		},
		'json'
	);
}

