function uploadifySetCookie(cookieName, cookieValue) {
	var today = new Date();
	var expire = new Date();
	var nDays=1;
	expire.setTime(today.getTime() + 3600000*24*nDays);
	document.cookie = cookieName + "=" + escape(cookieValue) + ";expires=" + expire.toGMTString();
}

function uploadifyReadCookie(cookieName) {
	var theCookie = " " + document.cookie;
	var ind = theCookie.indexOf(" " + cookieName + "=");
	if (ind == -1){
		ind = theCookie.indexOf(";" + cookieName + "=");
	}
	if (ind == -1 || cookieName == ""){ 
		return "";
	}
	var ind1 = theCookie.indexOf(";", ind + 1);
	if (ind1 == -1){
		ind1 = theCookie.length;
	} 
	return unescape(theCookie.substring(ind + cookieName.length + 2, ind1));
}

function uploadifyShowError(id, msg){
	$('[id$="' + id + '"]').addClass('uploadifyError');
	$('[id$="' + id + '"] .percentage').html(' - ' + msg);
}

function uploadifySetDimensions(width, height){
	uploadifySetCookie('uploadifyUploaderWidth', width);
	uploadifySetCookie('uploadifyUploaderHeight', height);
}

function uploadifyHideUploader(elementID){
	$('#' + elementID + 'Uploader').height(0);
	$('#' + elementID + 'Uploader').width(0);
}

// to use this function first call uploadifySetDimensions(...) !!!
function uploadifyShowUploader(elementID){
	$('#' + elementID + 'Uploader').height(uploadifyReadCookie('uploadifyUploaderHeight'));
	$('#' + elementID + 'Uploader').width(uploadifyReadCookie('uploadifyUploaderWidth'));
}



function uploadifyUploadImgOnComplete(event, ID, fileObj, response, data, elementID){
	uploadifyHideUploader(elementID);
	if(response.data.thumb_src){
		uploadifyUploadImgShowPreview(elementID, response.data.thumb_src);
	} else {
		uploadifyUploadImgShowPreview(elementID, response.data.src);
	}
	$('#' + elementID).val(response.data.src);
	$('#' + elementID + 'ThumbSrc').val(response.data.thumb_src);
	$('#' + elementID + 'Id').val(response.data.id);
	$('#' + elementID).parent().removeClass('error');
	$('#' + elementID).parent().find('.error-message').each(function(){
		$(this).remove();
	});
}

function uploadifyUploadImgRemoveImg(elementID, path){
	$('#' + elementID + 'Cross').remove();
	$('#' + elementID + 'ImagePreview').append('<div class="ajax_wait" id="' + elementID + 'AjaxLoader"></div>');
	$.ajax({
		url: '/attachments/delete',
		context: $('#' + elementID + 'ImagePreview'),
		dataType: 'json',
		type: 'POST',
		data: 'src=' + path + '&id=' + $('#' + elementID + 'Id').val(),
		success: function(data, textStatus, jqXHR){
			if(data.type == "ack"){
				$(this).remove();
				$('#' + elementID).val('');
				$('#' + elementID + 'ThumbSrc').val('');
				$('#' + elementID + 'Id').val('');
				uploadifyShowUploader(elementID);
			} else {
				$('#' + elementID + 'AjaxLoader').remove();
				alert("Nie udało się usunąć obrazka: " + data.data);
			}
		},
		error: function(){
			$('#' + elementID + 'AjaxLoader').remove();
			alert('Wystąpił błąd podczas usuwania obrazka.');
		}
	});
}

function uploadifyUploadImgShowPreview(elementID, path){
	var preview = '<div class="uploadifyImgPreview" id="' + elementID + 'ImagePreview">' + 
					  '<img src="' + path + '" />' +
					  '<div class="cross" id="' + elementID + 'Cross"></div>' +
				  '</div>';
	$('#' + elementID).hide();
	$(preview).insertAfter($('#' + elementID).parent().find('label').first());
	$('#' + elementID + 'Cross').click(function(){
		if(confirm("Czy na pewno chcesz usunąć ten obrazek?")){
			uploadifyUploadImgRemoveImg(elementID, path);
		}
	});
}

function uploadifyGalleryUploadOnComplete(event, ID, fileObj, response, data, contenerId, type){
	var template = '<div id="Attachment%key%" class="gallery_element">' +
					  '<div class="input textarea">' +
					    '<label for="Attachment%key%Desc">Opis:</label>' +
					    '<textarea name="data[Attachment][%key%][desc]" onkeyup="uploadifyGalleryUploadTextareaKeyUp(this);" cols="30" rows="6" id="Attachment%key%Desc"></textarea>' +
					  '</div>' +
					  '<input type="hidden" name="data[Attachment][%key%][thumb_src]" id="Attachment%key%ThumbSrc" value="%thumb_src%">' +
					  '<input type="hidden" name="data[Attachment][%key%][src]" id="Attachment%key%Src" value="%src%">' +
					  '<input type="hidden" name="data[Attachment][%key%][id]" id="Attachment%key%Id" value="' + response.data.id + '">' +
					  '<input type="hidden" name="data[Attachment][%key%][order]" id="Attachment%key%Order" value="%order%">' +
					  '<input type="hidden" name="data[Attachment][%key%][type]" value="' + type + '" id="Attachment%key%Type">' +
					  '<div class="gallery_img_preview">' +
					    '<a href="%src%" rel="' + contenerId + '">' +
					      '<img src="%thumb_src%" alt="">' +
					    '</a>' +
					  '</div>' +
					  '<div class="clear_all"></div><div id="Attachment%key%ArrowUp" class="arrow arrow_up"></div><div id="Attachment%key%ArrowDown" class="arrow arrow_down"></div><div id="Attachment%key%Cross" class="cross"></div>' +
					'</div>';
			
	var nextData = uploadifyGalleryUploadGetNextData();
	var key = nextData.key;
	template = template.replace(/%key%/gi, key);
	template = template.replace(/%thumb_src%/gi, response.data.thumb_src);
	template = template.replace(/%order%/gi, nextData.order);
	template = template.replace(/%src%/gi, response.data.src);
	$('#' + contenerId + 'UploadedImages').append(template);
	$('#' + contenerId + 'UploadedImages'  + " a[rel='" + contenerId + "']").colorbox({opacity: 0.90, slideshow: true, slideshowAuto: false, slideshowSpeed: 5000, transition: 'none'});
	uploadifyGalleryUploadBindActions('Attachment' + key);
}

function uploadifyGalleryUploadTextareaKeyUp(textarea){
	var id = textarea.id;
	var ta_val = $('#' + id).val();
	if(ta_val.length > 255){
		$('#' + id).val(ta_val.substr(0, 255));
	}
	$('#' + id).parent().parent().find('.gallery_img_preview a').attr('title', ta_val);
}

function uploadifyGalleryUploadRemoveImg(id){
	$('#' + id + 'Cross').remove();
	$('#' + id + ' .arrow').each(function(){
		$(this).remove();
	});
	$('#' + id + 'Desc').attr('disabled', 'disabled');
	$('#' + id + 'Desc').addClass('disabled');
	$('#' + id).append('<div class="ajax_wait"></div>');
	$.ajax({
		url: '/attachments/delete',
		context: $('#' + id),
		dataType: 'json',
		type: 'POST',
		data: 'src=' + $('#' + id + 'Src').val() + '&id=' + $('#' + id + 'Id').val(),
		success: function(data, textStatus, jqXHR){
			if(data.type == "ack"){
				$(this).find('.ajax_wait').remove();
				$(this).slideUp(500, function(){
					$(this).remove();
				});
			} else {
				$(this).remove();
				alert('Błąd podczas usuwania pliku.');
			}
		},
		error: function(){
			uploadifyGalleryUploadOnAjaxError(id);
			alert('Błąd podczas usuwania pliku.');
		}
	});
}

function uploadifyGalleryUploadOnAjaxError(id){
	$('#' + id).find('.ajax_wait').first().remove();
	$('#' + id + 'Desc').removeClass('disabled');
	$('#' + id + 'Desc').removeAttr('disabled');
	$('#' + id).append('<div id="' + id + 'ArrowUp" class="arrow arrow_up"></div><div id="' + id + 'ArrowDown" class="arrow arrow_down"></div><div id="' + id + 'Cross" class="cross"></div>');
	uploadifyGalleryUploadBindActions(id);
}

function uploadifyGalleryUploadGetNextData(){
	var max_key = -1;
	var max_order = -1;
	
	$('form .gallery_element [id$="Order"]').each(function(){
		order = parseInt($(this).val());
		if (order > max_order){
			max_order = order;
		}
	});
	
	$('form [id^="Attachment"]').each(function(){
		try{
			key = parseInt($(this).attr('id').substr("Attachment".length));
			if (key > max_key){
				max_key = key;
			}
		} catch (err) {}
	});
	
	return {key:max_key + 1, order:max_order + 1};
}

function uploadifyGalleryUploadBindActions(id){
	$('#' + id + 'Cross').click(function(){
		if(confirm("Czy na pewno chcesz usunąć ten obrazek?")){
			uploadifyGalleryUploadRemoveImg(id);
		}
	});
	
	$('#' + id + 'ArrowUp').click(function(){
		if($(this).parent().prev().size() > 0){
			var this_order = $(this).parent().find('[id$="Order"]').first().val();
			$(this).parent().find('[id$="Order"]').first().val($(this).parent().prev().find('[id$="Order"]').first().val());
			$(this).parent().prev().find('[id$="Order"]').first().val(this_order);
			$(this).parent().swap($(this).parent().prev());
		}
	});
	
	$('#' + id + 'ArrowDown').click(function(){
		if($(this).parent().next().size() > 0){
			var this_order = $(this).parent().find('[id$="Order"]').first().val();
			$(this).parent().find('[id$="Order"]').first().val($(this).parent().next().find('[id$="Order"]').first().val());
			$(this).parent().next().find('[id$="Order"]').first().val(this_order);
			$(this).parent().swap($(this).parent().next());
		}
	});
}

