var filtersSubmited = false;

$(document).ready(function() {
	$('.tbl').fixedtableheader();

	(function() {
		var po = document.createElement('script'); po.type = 'text/javascript'; po.async = true;
		po.src = 'https://apis.google.com/js/plusone.js';
		var s = document.getElementsByTagName('script')[0]; s.parentNode.insertBefore(po, s);
	})();
}); 

$(function() {
	$('#f_buyitnow').click(function() {
		if ($(this).attr('checked')==true) $('#f_paypal_email').attr('disabled', false);
		else $('#f_paypal_email').attr('disabled', true);
	});

	$('#ad_message_link a').click(function () { 
		$('#ad_message_link').hide();
		$('#ad_message').show();
	});

	$('.ad_list').hover(function () { 
		$(this).parent('.ad_container').css('background-color','#F4F4F4');
	}, function() { 
		$(this).parent('.ad_container').css('background-color','#ffffff');
	});

	$('a[rel]').overlay({'top':'10%'});

	// filters subcategories qtip
	$('.filters_parent_category a[title]').qtip({
		show: { when: 'mouseover', delay: 0 },
		hide: { when: 'mouseout', fixed: true, delay: 0 },
		content: { prerender: true },
		text: false, // Use each elements title attribute
		position: {
			corner: {
				tooltip: 'leftTop', // Use the corner...
				target: 'topRight' // ...and opposite corner
			},
			adjust: { x: -10, y: 0 }
		},
		style: {
			border: {
				width: 1,
				radius: 1
			},
			background: '#f1f1f1',
			padding: 3,
			width: 250,
			tip: true
		}
	});

	if ($('#ad_id').length>0) {
		var adID = $('#ad_id b').html();

		var arr = new Array();

		if ($.cookie('visited_ads')) arr = $.cookie('visited_ads').split(',');

		arr = jQuery.grep(arr, function(value) {
			if (value && value!='null' && value!=adID) return value;
		});

		var cookie_value;

		if (arr.length>0) cookie_value = arr.join(',')+','+adID;
		else cookie_value = adID;

		var options = { path: '/', expires: 14 };
		$.cookie('visited_ads', cookie_value, options);
	}

	$('#ad_url input').click(function () { 
		$(this).select()
	});

	// text disable
	$('.disableSelection, #filters span').not( $('input') ).disableTextSelect();
	
	// menu+filters hover
	$('ul.filters li .title, .menu, .menu_active').hover(function () { $(this).addClass('hover'); }, function() { $(this).removeClass('hover'); });
	// ads list hover
	$('.ad_list_title_container').hover(function () { $(this).addClass('hover'); }, function() { $(this).removeClass('hover'); });
	
	$('#u_captcha').attr('autocomplete', 'off');
	$('#change-image').click(function () {
		$('#captcha').attr('src',PAGE_PATH+'web/class/cool-php-captcha/captcha.php?'+Math.random());
		$('#u_captcha').focus();
	});
	$('#change-image-bg').click(function () {
		$('#captcha').attr('src',PAGE_PATH+'web/class/cool-php-captcha/captcha.php?bg&'+Math.random());
		$('#u_captcha').focus();
	});

	// clear search field
	$('#clear_search').click(function () {
		$('#search_field').val('');
		$('#search_field').focus();
		$(this).hide();
	});

	if ($('#search_field').val()!='') $('#clear_search').show(); else $('#clear_search').hide();

	$('#search_field').keyup(function (event) {
		if ($(this).val()!='') $('#clear_search').show(); else $('#clear_search').hide();
		if (event.keyCode == 27) {
			$(this).val('');
			$('#clear_search').hide();
		}
	});

	$('#search_field').blur(function () {
		if ($('#search_field').val()!='') $('#clear_search').show(); else $('#clear_search').hide();
	});

	// input focus
	$('.input, .input_search, textarea, select').focus(
		function() {
			$(this).addClass('input_focus');
		}
	);

	$('.input, .input_search, textarea, select').blur(
		function() { 
			$(this).removeClass('input_focus');
		}
	);

	// stylingButtons
	var buttonOptions={
		checkButtonset:true,
		size:'normal'
	};
	$('.ui-button').button(buttonOptions);

	var buttonOptionsNormal={
		checkButtonset:true,
		size:'huge'
	};
	$('.ui-buttonsizenormal').button(buttonOptionsNormal);
	// END - stylingButtons

	$('form').submit(function() {
		$('button').button('option','disabled', true);
	});

	$('.showHidden').click(function() {
		if ($(this).html()==translations['General_ExpandSelection']) {
			$(this).parents('.content').children('.hide').show();
			$(this).html(translations['General_NarrowSelection']);
		} else {
			$(this).parents('.content').children('.hide').hide();
			$(this).html(translations['General_ExpandSelection']);
		}
	});

	$('#u_kategorija').change(function() {
		get_subcategories(this.value, '', '0', {'target':'div_sub_kategorija','preloader':'prsub','clear_content': true});
	});

	$("#f_premium").attr("checked", false);
	$('#f_premium').click(function() {
		if ($(this).attr('checked')==true) {
			$('#amount').val( eval($('#amount').val())+eval($('#premium_price').val()) );
			$('#custom').val( $('#custom_default').val()+"1" );
			if ( eval($('#amount').val())==eval($('#premium_price').val()) ) $('#paypal_submit').show();
		} else {
			$('#amount').val( eval($('#amount').val())-eval($('#premium_price').val()) );
			$('#custom').val( $('#custom_default').val() );
			if (eval($('#amount').val()<0)) $('#amount').val("0");
			if ( $('#amount').val()=="0" ) $('#paypal_submit').hide();
		}
	});
});

// Uploadify
$(function(){
	if ($('#uf_images').length!=0) {
		$('#uf_images').uploadify({
			'uploader'	: '/web/js/jquery.uploadify/uploadify.swf',
			'script'	: '/web/files/uploadify.php',
			'cancelImg'	: '/web/js/jquery.uploadify/cancel.png',
			'folder'	: '/'+$('#h_adID').val(),
			'buttonImg'	: '/web/js/jquery.uploadify/browse-files.png',
			'wmode'		: 'transparent',
			'width'		: 194,
			'height'	: 45,
			'queueID'	: 'fileQueue',
			'auto'		: true,
			'multi'		: true,
			'sizeLimit'	: 10*1024*1024,
			'fileDesc'	: '.png, .jpg',
			'fileExt'	: '*.png;*.jpg',
			'onSelectOnce'	: function(event, data) { $('#step2_submit').button('option','disabled', true); $('#images_container').html(''); },
			'onCancel'	: function(event, queueID, fileObj, data) { if (data['fileCount']==0) { $('#step2_submit').button('option','disabled', false);  return_ad_images({'target':'images_container','preloader':'pr_images','clear_content': true}); } },
			'onError'	: function(event, queueID, fileObj, errorObj) { if (errorObj['type']=='File Size') { alert('"'+fileObj['name']+'" '+translations['General_ErrorFilesize']); $('#uf_images').uploadifyCancel(queueID); $('#uf_images').uploadifyUpload(); } else alert(translations['General_ErrorUploadFailed']); },
			'onComplete'	: function(event, queueID, fileObj, response, data) { if (response!=1) alert(response); },
			'onAllComplete'	: function(event, data) { if (data['errors']==0) { $('#step2_submit').button('option','disabled', false);  return_ad_images({'target':'images_container','preloader':'pr_images','clear_content': true}); } }
		});
	} 
});

// clear filter when not submitted
function clearFilter(elemID) {
	$('#'+elemID+' input[type=checkbox]').attr('checked',false);
	$('#'+elemID+' input[type=text]').val('');
	checkGroups();
	sendForm('filters_form');
}

// function getCheckboxVal
jQuery.fn.getCheckboxVal = function(){ 
    var vals = '';
    this.each(function(){ 
        vals+= jQuery(this).val()+',';
    }); 
    return vals; 
}
// function getCheckboxId
jQuery.fn.getCheckboxId = function(){ 
	var ids = '';
	this.each(function(){ 
		ids+= $(this).attr("id").substr(3)+',';
	}); 
	return ids;
}

function delete_ad(adtext){
	return confirm('"'+adtext+'" '+translations['General_ConfirmDelete']);
}

// submit filters form
function sendForm(form){  
	if (!filtersSubmited) {
		var plx = new PHPLiveX();  
		$('.atnaujinti').button('option','disabled', false);
		return plx.SubmitForm(form, {'target':'atnaujinti','preloader':'pr','clear_content': false,'onUpdate':function(result){ $('.atnaujinti').children('.ui-button-label').html(result); fade( $('.atnaujinti').children('.ui-button-label') ); }});
	}
}

function fade(elem) {
	var originalColor = "#333333";
	var fadeColor = "#FFBC00"; 
	
	elem.animate({color:fadeColor}, 500); elem.animate({color:originalColor}, 500);
}

// check group if it has checked filters to change the color
function checkGroups() {
	$('.content').each(function(){
		var inputElems = $('#'+jQuery(this).attr('id')+' input[type=\'text\']');
		var filledElems = 0;
		inputElems.each(function(){ 
			if (jQuery(this).val()!='') filledElems++;
		});

		var checkedElems = $('#'+jQuery(this).attr('id')+' input:checkbox:checked').length;
		if (checkedElems>0 || filledElems>0) {
			jQuery(this).parents('li').children('.title').addClass('fg_title_modified');
			jQuery(this).parents('li').children('.remove').show();
		} else {
			jQuery(this).parents('li').children('.title').removeClass('fg_title_modified');
			jQuery(this).parents('li').children('.remove').hide();
		}
	});
}

// check all checkboxes of group
function checkAllFilters(clickedElemID) {
	var pazymeta = '';
	$('.'+clickedElemID).each(function(){
		if ($('#'+clickedElemID).is(':checked')) pazymeta = 'checked'; else pazymeta = '';
		$(this).attr('checked',pazymeta);
	});
}

// on ready
$(function(){
	$('.atnaujinti').click(function () {
		$('#filters_form').attr('action', ''); $('#filters_form').submit(); this.disabled=true;
	});

	$('#filters_form').submit(function () {
		filtersSubmited = true;
		$('#filters_form').attr('action', '');
	});

	var TimerId3 = 0;
	/* star/unstar ad */
	$('.ad_star,.ad_list_star').click(function () {
		if (!$(this).attr('onclick')) {
			var adID = $(this).attr('id').substr(5);
			var originalColor = "#333333";
			var fadeColor = "#FFBC00"; 

			clearTimeout(TimerId3);

			if ($(this).hasClass('star')) {
				TimerId3 = setTimeout(function(){ ajaxStarAd(adID,'0',{'target':'starredCount','onUpdate':function(){ $("#starredCountLink").animate({color:fadeColor}, 500);$("#starredCountLink").animate({color:originalColor}, 500); } }); },300);

				$(this).removeClass('star'); 
				$(this).addClass('star_off');
				$(this).attr('title',translations['General_StarAd']);
				$('#a_star_'+adID).html(translations['General_StarAd']);
			} else {
				TimerId3 = setTimeout(function(){ ajaxStarAd(adID,'1',{'target':'starredCount','onUpdate':function(){ $("#starredCountLink").animate({color:fadeColor}, 500); $("#starredCountLink").animate({color:originalColor}, 500); } }); },300);

				$(this).removeClass('star_off'); 
				$(this).addClass('star');
				$(this).attr('title',translations['General_UnstarAd']);
				$('#a_star_'+adID).html(translations['General_UnstarAd']);
			}
			return false;
		}
	});
	/* END - star/unstar ad */
});

function star_from_link(elem) {
	var adID = elem.parents('.ad_container').attr('id').substr(2);
	var originalColor = "#333333";
	if ($('#starredCountLink').parent().hasClass('menu_active')) originalColor = "#ffffff";
	var fadeColor = "#FFBC00"; 
	
	if ($('#star_'+adID).hasClass('star')) {
		ajaxStarAd(adID,'0',{'target':'starredCount','onUpdate':function(){ $("#starredCountLink").animate({color:fadeColor}, 500); $("#starredCountLink").animate({color:originalColor}, 500); } });
		$('#star_'+adID).removeClass('star'); 
		$('#star_'+adID).addClass('star_off');
		$('#star_'+adID).attr('title',translations['General_StarAd']);
		elem.html(translations['General_StarAd']);
	} else {
		ajaxStarAd(adID,'1',{'target':'starredCount','onUpdate':function(){ $("#starredCountLink").animate({color:fadeColor}, 500); $("#starredCountLink").animate({color:originalColor}, 500); } });
		$('#star_'+adID).removeClass('star_off');
		$('#star_'+adID).addClass('star'); 
		$('#star_'+adID).attr('title',translations['General_UnstarAd']);
		elem.html(translations['General_UnstarAd']);
	}
	return false;
}

function minimize_ad(elem) {
	var ad_data_list_div = elem.parents('.ad_container').children().children('.ad_data_list');
	ad_data_list_div.css('display','none');
	elem.parents('.ad_inner').removeClass('active_ad');
}

// form submits
$(function(){
	// logout
	$("#logout").click(function() {
		$("#form_logout").submit();
	});
	
	// on filters change recount results
	var TimerId1 = 0;
	$('#filters_form select').change(function () {
		clearTimeout(TimerId1);
		TimerId1 = setTimeout(function(){sendForm('filters_form')},500);
	});
	$('#filters_form input[type=checkbox]').click(function () {
		clearTimeout(TimerId1);
		TimerId1 = setTimeout(function(){sendForm('filters_form')},500);
		checkGroups();
	});
	$('#filters_form input[type=text]').keyup(function () {
		clearTimeout(TimerId1);
		TimerId1 = setTimeout(function(){sendForm('filters_form')},500);
		checkGroups();
	});
	$(document).ready(function(){ 
		checkGroups();
	});
	// END - on filters change recount result
});
