jQuery(function($) {
	// Framework
	
	(function() {
		if ('undefined' === typeof window.console) {
			window.console = {};
		}
		
		var console_functions = [
			'log', 'debug', 'info', 'warn', 'error', 'assert', 'dir', 'dirxml', 'trace',
			'group', 'groupCollapsed', 'groupEnd', 'time', 'timeEnd', 'profile', 'profileEnd',
			'count', 'exception', 'table'
		];
		
		$
			.each(console_functions, function(k, v) {
				if ('function' !== typeof window.console[v]) {
					window
						.console[v] = $
							.noop;
				}
			});
	})();
	
	$
		.extend(
			true,
			{
				getXML: function(url, data, callback) {
					$.get(url, data, callback, 'xml');
				},
				getHTML: function(url, data, callback) {
					$.get(url, data, callback, 'html');
				},
				getJSONP: function(url, data, callback) {
					$.get(url, data, callback, 'jsonp');
				},
				getText: function(url, data, callback) {
					$.get(url, data, callback, 'text');
				},
				postXML: function(url, data, callback) {
					$.post(url, data, callback, 'xml');
				},
				postHTML: function(url, data, callback) {
					$.post(url, data, callback, 'html');
				},
				postScript: function(url, data, callback) {
					$.post(url, data, callback, 'script');
				},
				postJSON: function(url, data, callback) {
					$.post(url, data, callback, 'json');
				},
				postJSONP: function(url, data, callback) {
					$.post(url, data, callback, 'jsonp');
				},
				postText: function(url, data, callback) {
					$.post(url, data, callback, 'text');
				}
			}
		)
		.ajaxSetup({
			cache: false
		});
	
	$('.target_blank')
		.attr({
			'target': '_blank'
		});
		
	$('.confirm')
		.each(function() {
			var $this = $(this);
			var message = $this.attr('title') || 'Are you sure?';
			
			$this
				.click(function(e) {
					if (!confirm(message)) {
						e
							.preventDefault();
					}
				});
		})
		.removeAttr('title');

		//add ADS
		var addButton = $('#add');
		
		addButton.click(function() {
			$('#addButton').addClass('hidden');
			$('#addLoading').removeClass('hidden');
			$
				.postJSON(
					'/ajax/add.php',
					{
						'title': $('input#title').val(),
						'description': $('textarea#description').val(),
						'category': $("input[name=category]:checked").val(),
						'price': $('#price').val(),
						'locale': $('input#locale').val(),
						'phone': $('input#phone').val(),
						'delivery_by': $("input[name=delivery_by]:checked").val(),
					},						
					function(receivedData) {
						
						$('#addError').html('');
						if ('title' === receivedData.status) {
							$('#addError').html('Моля попълнете коректно заглавието !');$('#addButton').removeClass('hidden');
						}else if ('description' === receivedData.status) {
							$('#addError').html('Моля попълнете коректно описанието !');$('#addButton').removeClass('hidden');
						}else if ('category' === receivedData.status) {
							$('#addError').html('Моля изберете категория !');$('#addButton').removeClass('hidden');
						}else if ('price' === receivedData.status) {
							$('#addError').html('Моля попълнете коректно цената !');$('#addButton').removeClass('hidden');
						}else if ('locale' === receivedData.status) {
							$('#addError').html('Моля попълнете коректно мястото !');$('#addButton').removeClass('hidden');
						}else if ('phone' === receivedData.status) {
							$('#addError').html('Моля попълнете коректно телефонният номер !');$('#addButton').removeClass('hidden');
						}else if ('success' === receivedData.status) {
							$('#adsId').val(receivedData.newId);
							$('#addFinish').attr("href", "/details/" + receivedData.newId)
							$('#addOneStep').html('').addClass('hidden');
							$('#addStepTwo').removeClass('hidden');
						}
						$('#addLoading').addClass('hidden');
					}
				);
		});
		
	//End add

	//edit ADS
		var addButton = $('#edit');
		
		addButton.click(function() {
			$('#addButton').addClass('hidden');
			$('#addLoading').removeClass('hidden');
			$
				.postJSON(
					'/ajax/edit.php',
					{
						'title': $('input#title').val(),
						'adsId': $('input#adsId').val(),
						'description': $('textarea#description').val(),
						'category': $("input[name=category]:checked").val(),
						'price': $('#price').val(),
						'locale': $('input#locale').val(),
						'phone': $('input#phone').val(),
						'delivery_by': $("input[name=delivery_by]:checked").val(),
					},						
					function(receivedData) {
						
						$('#addError').html('');
						if ('title' === receivedData.status) {
							$('#addError').html('Моля попълнете коректно заглавието !');$('#addButton').removeClass('hidden');
						}else if ('description' === receivedData.status) {
							$('#addError').html('Моля попълнете коректно описанието !');$('#addButton').removeClass('hidden');
						}else if ('category' === receivedData.status) {
							$('#addError').html('Моля изберете категория !');$('#addButton').removeClass('hidden');
						}else if ('price' === receivedData.status) {
							$('#addError').html('Моля попълнете коректно цената !');$('#addButton').removeClass('hidden');
						}else if ('locale' === receivedData.status) {
							$('#addError').html('Моля попълнете коректно мястото !');$('#addButton').removeClass('hidden');
						}else if ('phone' === receivedData.status) {
							$('#addError').html('Моля попълнете коректно телефонният номер !');$('#addButton').removeClass('hidden');
						}else if ('success' === receivedData.status) {
							$('#adsId').val(receivedData.newId);
							$('#addFinish').attr("href", "/details/" + receivedData.newId)
							$('#addOneStep').html('').addClass('hidden');
							$('#addStepTwo').removeClass('hidden');
						}
						$('#addLoading').addClass('hidden');
					}
				);
		});
		
	//End add
	
	//upload img
	$('#upload').click(function(){
		var btnUpload=$('#upload');
		var status=$('#status');
		new AjaxUpload(btnUpload, {
			action: '/imgUpload.php?adsId=' + $('input#adsId').val(),
			name: 'uploadfile',
			onSubmit: function(file, ext){
				 if (! (ext && /^(jpg|png|jpeg|gif)$/.test(ext))){ 
                    // extension is not allowed 
					status.text('Only JPG, PNG or GIF files are allowed');
					return false;
				}
				status.text('Uploading...');
			},
			onComplete: function(file, response){
				//On completion clear the status
				status.text('');
				//Add uploaded file to list
				if(response.substring(0, 7)==="success"){
					var file = response.substring(8);
					$('<li></li>').appendTo('#files').html('<img src="'+file+'" alt="" style="width: 80px;" />').addClass('success');
				}else if(response === "max"){
					$('<li></li>').appendTo('#files').text('Имате 5 качени снимки !').addClass('error');
				}else{
					$('<li></li>').appendTo('#files').text(file).addClass('error');
				}
			}
		});
		
	});
	
	//edit del img
	
	$('div[id^="del_"]')
		.click(function() {
			var $this = $(this);
			var artId = $this.attr('id').substring(4);
			
			$
				.postJSON(
					'/ajax/delImg.php',
					{
						'artId': artId
					},
					function(receivedData) {
						
						if (1 === receivedData.status) {
							$('#thisDel_' + receivedData.imgId)
								.text('')
						}
					}
				);
		});
		
	//vote profile
	$('.positive')
		.click(function() {
			var $this = $('div[id^="vote_"]');
			var userId = $this.attr('id').substring(5);
			var addVote = $('span#score');
			
			$
				.postJSON(
					'/ajax/vote.php',
					{
						'userId': userId,
						'vote': 1
					},
					function(receivedData) {
						
						if (1 === receivedData.status) {
							var vote = parseInt(addVote.text());
							addVote
								.text(vote + 1)
						}
					}
				);
		});
		
	$('.negative')
		.click(function() {
			var $this = $('div[id^="vote_"]');
			var userId = $this.attr('id').substring(5);
			var addVote = $('span#score');
			
			$
				.postJSON(
					'/ajax/vote.php',
					{
						'userId': userId
					},
					function(receivedData) {
						
						if (1 === receivedData.status) {
							var vote = parseInt(addVote.text());
							addVote
								.text(vote - 1)
						}
					}
				);
		});
	
	//popup VIP
	//0 means disabled; 1 means enabled;
	var popupStatus = 0;

	//disabling popup with jQuery magic!
	function disablePopup(){
		//disables popup only if it is enabled
		if(popupStatus==1){
			$("#popup_background").fadeOut("fast");
			$("#pop").fadeOut("fast");
			popupStatus = 0;
		}
	}


	//CONTROLLING EVENTS IN jQuery
	$(document).ready(function(){
		
		//LOADING POPUP
		//Click the button event!
		$('#show_pop').click(function(){
		//request data for centering
			var windowWidth = document.documentElement.clientWidth;
			var windowHeight = document.documentElement.clientHeight;
			var popupHeight = $("#pop").height();
			var popupWidth = $("#pop").width();
			//centering
			$("#pop").css({
				"position": "fixed",
				"top": windowHeight/2-popupHeight/2,
				"left": windowWidth/2-popupWidth/2
			});
			//only need force for IE6
			
			$("#popup_background").css({
				"height": windowHeight
			});
			//load popup
			//loads popup only if it is disabled
			if(popupStatus==0){
				$("#popup_background").css({
					"opacity": "0.7"
				});
				$("#popup_background").fadeIn("fast");
				$("#pop").fadeIn("fast");
				popupStatus = 1;
			}
		});
		
		//CLOSING POPUP
		
		//Click the x event!
		$("#pop_close").click(function(){
			disablePopup();
		});
		
		//Click out event!
		$("#popup_background").click(function(){
			disablePopup();
		});
		
		//Press Escape event!
		$(document).keypress(function(e){
			if(e.keyCode==27 && popupStatus==1){
				disablePopup();
			}
		});

	});
	
});
