var AppConfig = {
		applicationName: 'index.php',
		moduleName: 'remote',
		shiftKey: 0,
		ctrlKey: 0,
		logged: 0,
		modId: 0,
		catId: 0,
		animation: 1,
		init: function() {
			this.hostPath = window.location.protocol + '//' + window.location.host;
			this.pathName = window.location.pathname;
		}
};
var AppParams = {
		applicationName: 'administration.php',
		busy: 0,
		shiftKey: 0,
		ctrlKey: 0,
		logged: 0,
		modId: 0,
		catId: 0,
		layoutId: 0,
		routeId: 0,
		sectionId: 0,
		basedId: 0,
		elementId: new Object(),
		dblClick: 0,
		animation: 1,
		imagesLibrary: 0,
		imageInputId: '',
		downloadCategoryId: 0,
		folderParentId: new Array(),
		currentFolders: new Array(),
		explorerMaxId: 0,
		fileUploadPath: '',
		folderSelected: new Array(),
		folderAdd: 0,
		uploadTotal: 0,
		uploadCurrentTotal: 0,
		imageAdministrationBlockId: '',
		init: function() {
			this.hostPath = window.location.protocol + '//' + window.location.host + '/';
		}
};

function controls_manual_change_color(event, element, selector, rule, id) {

	key = event.which | window.event;

	if(key == '13' && Flexi(element).val().match(/#[0-9a-f]{6}/)) {
		jQuery(selector).css('background-color', Flexi(element).val());
		Flexi('#color_picker_color_choice_' + id).css('background-color', Flexi(element).val());
		Flexi.post('/main/updateCss/', { color: Flexi(element).val(), id: id }, function(data) {
			var selectors = data.split(',');
			for(var i = 0; i < selectors.length; i++) {
				Flexi(selectors[i]).css(rule, Flexi(element).val());
			}
		});
	}

}
function controls_bgPosition(position, draggable) {
	//alert(draggable.params.data.params.data.selector);
	//alert(draggable.params.data.params.data.rule);

	var current = jQuery(draggable.params.data.params.data.selector).css('background-position');
	var parts = current.split(' ');
	//alert(position + ' ' + parts[1]);
	if(draggable.params.data.params.data.rule == 'background-position-x') {
		jQuery(draggable.params.data.params.data.selector).css('background-position', position + draggable.params.data.params.units + ' ' + parts[1]);
	} else if(draggable.params.data.params.data.rule == 'background-position-y') {
		jQuery(draggable.params.data.params.data.selector).css('background-position', parts[0] + ' ' + position + draggable.params.data.params.units);
	}
}
function controls_bgRepeat(selector, id) {
	var repeat = 'no-repeat';
	if(jQuery('#background_repeat_x_' + id + ':checked').length && jQuery('#background_repeat_y_' + id + ':checked').length) {
		repeat = 'repeat';
	} else if(jQuery('#background_repeat_x_' + id + ':checked').length) {
		repeat = 'repeat-x';
	} else if(jQuery('#background_repeat_y_' + id + ':checked').length) {
		repeat = 'repeat-y';
	}
	Flexi.post('/main/updateCss/', { repeat: repeat, id: id }, function(data) {
		var selectors = data.split(',');
		for(var i = 0; i < selectors.length; i++) {
			Flexi(selectors[i]).css('background-repeat', attachment);
		}
	});
}
function controls_bgFixed(selector, id) {
	var attachment = 'scroll';
	if(jQuery('#background_fixed_' + id + ':checked').length) {
		attachment = 'fixed';
	}
	Flexi.post('/main/updateCss/', { attachment: attachment, id: id }, function(data) {
		var selectors = data.split(',');
		for(var i = 0; i < selectors.length; i++) {
			Flexi(selectors[i]).css('background-attachment', attachment);
		}
	});
	//jQuery(selector).css('background-attachment', attachment);
}
function controls_HSL(position, draggable) {
	var hue = Flexi('#hsl_hue_value_' + draggable.params.data.params.data.id).val();
	var saturation = Flexi('#hsl_saturation_value_' + draggable.params.data.params.data.id).val();
	var lightness = Flexi('#hsl_lightness_value_' + draggable.params.data.params.data.id).val();
	Flexi('html').css('cursor', 'busy');
	Flexi.post('/main/hslFilter/', { hue:  hue, saturation: saturation, lightness: lightness, id: draggable.params.data.params.data.id}, function(data) {
		//alert(data.toSource());
		var selectors = data.split(',');
		for(var i = 0; i < selectors.length; i++) {
			var bg = jQuery(selectors[i]).css('background-image');
			bg = bg.replace('url(', '').replace(')', '');
			while(bg.match(/'/) || bg.match(/"/)) {
				bg = bg.replace('\'', '').replace('"', '');
			}

			if(bg.match(/\?[0-9]+/)) {
				var parts = bg.split('?');
				parts[1] = '?' + Math.floor(Math.random()*100000000);
				bg = parts[0] + '?' + parts[1];
			} else {
				bg = bg + '?' + Math.floor(Math.random()*100000000);
			}
			//alert(bg);

			Flexi(selectors[i]).css('background-image', 'url("' + bg + '")');
			Flexi('html').css('cursor', 'auto');
		}
	});
}
function controls_change_color(selector, rule, id, color) {
	Flexi('#color_picker_color_choice_' + id).css('background-color', color);
	Flexi('#color_picker_input_' + id).val(color);
	Flexi('#color_picker_' + id).toggle();

	Flexi.post('/main/updateCss/', { color: color, id: id }, function(data) {
		var selectors = data.split(',');
		for(var i = 0; i < selectors.length; i++) {
			Flexi(selectors[i]).css(rule, color);
		}
	});
}
function controls_change_text_color(selector, id, color) {
	Flexi('#color_picker_color_choice_' + id).css('background-color', color);
	Flexi('#color_picker_input_' + id).val(color);
	Flexi('#color_picker_' + id).toggle();
	Flexi('html').css('cursor', 'busy');
	Flexi.post('/main/imageFilter/', { color: color, id: id}, function(data) {
		var selectors = data.split(',');
		for(var i = 0; i < selectors.length; i++) {
			var bg = jQuery(selectors[i]).css('background-image');
			bg = bg.replace('url(', '').replace(')', '');
			while(bg.match(/'/) || bg.match(/"/)) {
				bg = bg.replace('\'', '').replace('"', '');
			}

			if(bg.match(/\?[0-9]+/)) {
				var parts = bg.split('?');
				parts[1] = '?' + Math.floor(Math.random()*100000000);
				bg = parts[0] + '?' + parts[1];
			} else {
				bg = bg + '?' + Math.floor(Math.random()*100000000);
			}

			Flexi(selectors[i]).css('background-image', 'url("' + bg + '")');
			Flexi('html').css('cursor', 'auto');
		}
	});

}
function rgbConvert(str) {
	   str = str.replace(/rgb\(|\)/g, "").split(",");
	   str[0] = parseInt(str[0], 10).toString(16).toLowerCase();
	   str[1] = parseInt(str[1], 10).toString(16).toLowerCase();
	   str[2] = parseInt(str[2], 10).toString(16).toLowerCase();
	   str[0] = (str[0].length == 1) ? '0' + str[0] : str[0];
	   str[1] = (str[1].length == 1) ? '0' + str[1] : str[1];
	   str[2] = (str[2].length == 1) ? '0' + str[2] : str[2];
	   return ('#' + str.join(""));
	}
function correctHeight(max_height,id) {
	if(jQuery('#' + id + ' > tbody').length) {
		jQuery('#' + id + ' > tbody').css('height', 'auto');
		if(jQuery('#' + id + ' > tbody')[0].offsetHeight > max_height) {
			jQuery('#' + id + ' > tbody').css('height', max_height + 'px');
		}
	}
	else {
		alert(id + ' tbody for this identifier doesn\'t exist');
	}
}
function add_drop_area(droppable, windowId) {
	droppable.addDropArea('#' + windowId, function(draggable, droppable) {
		//alert('bbbb');
		var parts = jQuery(droppable.selector)[0].id.split('_');
		var copy_string = '';
		for(var f = 0; f < AppParams.folderSelected.length; f++) {
			divider = (f == 0) ? '' : ':::';
			copy_string += divider + AppParams.folderSelected[f].type + ':' + AppParams.folderSelected[f].id;
		}
		//alert(copy_string);
		jQuery.ajaxSetup({async: true});
		jQuery.post('/index.php/user/fileCopy/', {folder_id: parts[parts.length - 1], copy_type: 'move', copy_string: copy_string}, function(data) {
			setTimeout(function() {
				new Effect.Fade('copy_window');
				setTimeout(function() {
					WindowInterface.Windows['copy_window'].close();
					delete WindowInterface.Windows['copy_window'];
				}, 1500);
			}, 5000);
			return false;
		});
		load_window('user', 'copy_window', this, 'copyFile', 'info_window', 'copy_window', 'Kopiowanie plików', '&w_buttons=off');

	});
}
function load_symfony_component(element, module, component, parameters) {

	//button_param = (parameters[1] !== undefined) ? "&param=" + parameters[1] : '';
	if(parameters[2] !== undefined) {
		button_param = "&param=" + parameters[2];
		jQuery(element).load('/remote/loadRemoteComponent?mod_type=' + module + '&contentId=' + parameters[1] + '&comp=' + component + '&mod_id=' + parameters[0] + button_param);
	} else {
		button_param = "&param=" + parameters[1];
		jQuery(element).load('/remote/loadRemoteComponent?mod_type=' + module + '&comp=' + component + '&mod_id=' + parameters[0] + button_param);
	}
}
function show_news_administration(mod_id) {
	jQuery('#news_administration_menu_' + mod_id).toggle();
}
function reset_navigation_bar() {
	load_window_partial('user_account', '#user_navigation_bar', '/remote/loadRemoteComponent?mod_type=user&comp=navigationBar', 4);
}
function folder_save(ev, which, parent_id) {
	var focused = ev.explicitOriginalTarget||document.activeElement;

	if(focused.className != 'folder_add') {
		jQuery.post('/user/folderSave', { parent_id:  parent_id, name: which.value}, function(data) {
			//jQuery('.window_left_pannel').append(data);
			//load_folder(parent_id);
			//AppParams.folderAdd = 0;
			if(data == '1') {
				jQuery('#explorer_right_block').load('/remote/loadRemoteComponent?mod_type=user&comp=exploreFolder&folderId=' + parent_id);
			} else {
				//alert(data);
				load_window('user', 'common_info_window', this, 'userCommonInfoWindow', 'info_window', 'common_info_window', '&nbsp;', '&w_buttons=off&info=' + data);
			}
		});
	}
}
function image_popup(which, max_width, max_height, image_height) {

	var cH = document.documentElement.clientHeight;
	var ScrollTop = document.body.scrollTop;
	if (ScrollTop == 0) {
	    if (window.pageYOffset)
	        ScrollTop = window.pageYOffset;
	    else
	        ScrollTop = (document.body.parentElement) ? document.body.parentElement.scrollTop : 0;
	}
	//alert(ScrollTop);
	var div = document.createElement('div');
	div.setAttribute('id', 'popup_master_div');
	div.className = 'image_popup_div';

	var img = document.createElement('img');
	if (which.src) {
		img.setAttribute('src', which.src);
	} else {
		img.setAttribute('src', which);
	}
	img.setAttribute('id', 'img_popup');
	//img.setAttribute('onclick', 'removeImagePopup()');
	div.appendChild(img);
	document.getElementsByTagName('BODY')[0].appendChild(div);

	//alert(img.offsetWidth);
	setTimeout(function() {


		jQuery('#img_popup').click(function() {
			removeImagePopup();
		});

		var imgH = img.offsetHeight;
		var imgW = img.offsetWidth;
		var divH = div.offsetHeight;
		var divW = div.offsetWidth;



		if (image_height != null) {
			var centerY = image_height/2;
		} else {
			var centerY = Math.round(cH/2);
		}
		//imgH = jQuery('#img_popup').css('height');
		//imgW = jQuery('#img_popup').css('width');

		if(imgH > divH) {
			jQuery('#img_popup').css('height', divH);
		}
		if(imgW > divW) {
			jQuery('#img_popup').css('width', divW);
		}

		//alert(imgH + ':' + imgW);
		jQuery('#img_popup').css('height', '1px');
		jQuery('#img_popup').css('width',  '1px');
		jQuery('#popup_master_div').css('width', '1px');
		jQuery('#popup_master_div').css('height', '1px');
		jQuery('#popup_master_div').css('left', jQuery('#popup_master_div').css('left'));
		jQuery('#popup_master_div').css('top', centerY + 'px');

		jQuery('#popup_master_div').css('margin', ScrollTop + 'px 0 0 0');

		$('popup_master_div').morph({width: imgW + 'px', height: imgH + 'px'});
		$('img_popup').morph({width: imgW + 'px', height: imgH + 'px'});
		new Effect.Opacity('popup_master_div', { from: 0.01, to: 0.99});
		new Effect.Move('popup_master_div', { x: '-' + Math.round(parseInt(imgW)/2), y: '-' + Math.round(parseInt(imgH)/2), mode: 'relative' });
	}, 100);

}
function removeImagePopup() {
	jQuery('#popup_master_div').css('background-color', 'transparent');
	new Effect.Puff('img_popup', {duration: 0.7});
	setTimeout(function() {
		jQuery('#popup_master_div').remove();
	}, 720);
}
function offerPopup(width, height) {

	//var imgW = jQuery('.oferta_master')[0].offsetWidth + 'px';
	var imgW = '802px';
	var imgH = (jQuery('#jobOffer_body')[0].offsetHeight + jQuery('.offer_window_top')[0].offsetHeight + jQuery('.offer_window_footer')[0].offsetHeight) + 'px';

	jQuery('#jobOffer').css('width', imgW);
	jQuery('#jobOffer').css('height', imgH);
	jQuery('#jobOffer').css('overflow', 'hidden');
	jQuery('#jobOffer').css('width', '1px');
	jQuery('#jobOffer').css('height', '1px');
	jQuery('#jobOffer').css('top', '60px');
	jQuery('#jobOffer').css('left', Math.round(document.documentElement.clientWidth/2));

	setTimeout(function() {
		$('jobOffer').morph({width: imgW, height: imgH});
		new Effect.Opacity('jobOffer', { from: 0.01, to: 0.99});
		new Effect.Move('jobOffer', { x: '-' + Math.round(parseInt(imgW)/2), y: 0, mode: 'relative' });
	}, 700);

}
function post_copy(id) {
	jQuery('#answer').val(jQuery('#content'+id).html());
	return false;
}
function captcha_choice(which) {
	if(jQuery('input[name=captcha]').val() == "") {
		jQuery('input[name=captcha]').val(jQuery(which).html());
	}
	else {
		jQuery('input[name=captcha]').val(jQuery('input[name=captcha]').val() + ', ' + jQuery(which).html());
	}
}
function login(url) {
	window.location = url;
}
function login_pannel(mod_id) {
	jQuery('#ultra_modules_' + mod_id + '_body').toggle();
	return false;
}

function testUpload(file_id, selector_prefix) {
	done = jQuery('#lib_header22').html();
	var prefix = (typeof selector_prefix == 'undefined') ? '' : selector_prefix;
	//alert(done);
	//if(done != '') {
		//jQuery('#lib_header22').html('');
		if(file_id < 8) {
			if(jQuery('#file' + prefix +  '_' + parseInt(file_id + 1)).val()) {
				setTimeout("jQuery('#progress_bar_title').html('Ładowanie pliku:');", 600);
				setTimeout("jQuery('#progress_bar').css('width', '0px');", 600);
				setTimeout("jQuery('#progress_percentage').html('0%');", 600);
			}
			setTimeout("jQuery('#upload_form" + prefix +  '_' + parseInt(file_id + 1) + "').submit();", 600);
		} else {
			jQuery('#progress_bar_title').html('Ładowanie pliku:');
			jQuery('#progress_bar_title2').html('Ogólny postęp: &nbsp;<span class="upload_finished">zakończony</span>');
			//jQuery('.close_button').css('display', 'block');
			setTimeout(function() {
				WindowInterface.Windows['upload_progress_window'].close();
				delete WindowInterface.Windows['upload_progress_window'];
				//load_folder(AppParams.folderSelected);
				//$('helpers2').morph({width: '0px'});
				//setTimeout("scroll_end(1000, 0);", 1000);
				//jQuery('#lib_images_body')[0].scrollTop = jQuery('#lib_images_body')[0].scrollHeight - 300;
				//jQuery.ajaxSetup({async: false});
			}, 3000);
		}
//	}
//	else {
//		setTimeout("testUpload(" + file_id + ")", 400);
//	}
}
upload_total = 0;
full = 0;
i=0;
function testProgress(file_id, selector, selector_prefix) {
	var data = {
			current: 0,
			total: 0,
			filename: ''
	};
	jQuery.ajax({async: true});
	//jQuery.ajax({async: false});
	//data.current = data.total = 0;
	var select = (typeof selector == 'undefined') ? '#progress_key' + file_id : selector;
	var prefix = (typeof selector_prefix == 'undefined') ? '' : selector_prefix;

	var key = jQuery(select).val();
	jQuery.getJSON(AppConfig.hostPath + '/main/uploadProgress/?progress_key=' + key, function(data){

//		if(data.current > 1.2 * data.total) {
//			testProgress(file_id);
//		} else {
			width = parseInt(data.current/data.total * AppParams.uploadBarWidth) + 'px';

			full_width = parseInt((AppParams.uploadCurrentTotal + data.current)/AppParams.uploadTotal * AppParams.uploadBarWidth) + 'px';
			percentage = parseInt(data.current/data.total * 100) + '%';
			percentage_full = parseInt((AppParams.uploadCurrentTotal + data.current)/AppParams.uploadTotal * 1000) / 10  + '%';

			//alert(data.total + '<br />' + data.current + '<br />');

			i++;

			if(data.done || (data.current >= data.total && data.current > 0)) {

				var upload_finised = 1;
				for(var k = file_id + 1; k <= 8; k++) {
					if(jQuery('#file' + prefix + '_' + k).val()) {
						upload_finised = 0;
					}
				}
				AppParams.uploadCurrentTotal += data.total;
				if(upload_finised) {
					full_width = AppParams.uploadBarWidth + 'px';
					percentage_full = '100%';
				}
				//jQuery('.image_library_pannel_category_main').html(jQuery('.image_library_pannel_category_main').html() + '<br />Data current: ' + data.current + ' Data total:' + data.total + '<br />Full: ' + AppParams.uploadCurrentTotal + ' : ' + AppParams.uploadTotal);
				jQuery('#progress_bar_title').html('Uploading File: ' + data.filename);
				jQuery('#progress_percentage').html(percentage);
				jQuery('#progress_percentage2').html(percentage_full);

				jQuery('#progress_bar_title').html('Coping File: ' + data.filename);

				new Effect.Morph('progress_bar', {
					style: 'width: ' + width,
					duration: 0.3
				});
				new Effect.Morph('progress_bar2', {
					style: 'width: ' + full_width,
					duration: 0.3
				});

				setTimeout("testUpload(" + file_id + ", '" + prefix + "')", 400);
			} else {
				//jQuery('.image_library_pannel_category_main').html(jQuery('.image_library_pannel_category_main').html() + '<br />Data current: ' + data.current + ' Data total:' + data.total + '<br />Full: ' + AppParams.uploadCurrentTotal + ' : ' + AppParams.uploadTotal);
				jQuery('#progress_bar_title').html('Uploading File: ' + data.filename);
				jQuery('#progress_percentage').html(percentage);
				jQuery('#progress_percentage2').html(percentage_full);

				new Effect.Morph('progress_bar', {
					style: 'width: ' + width,
					duration: 0.3
				});
				new Effect.Morph('progress_bar2', {
					style: 'width: ' + full_width,
					duration: 0.3
				});

//				if(!upload_finised) {
//					setTimeout("testProgress(" + file_id + ")", 300);
//				} else {
//
//				}
					//jQuery('#progress_bar_title').html('Coping File: ' + data.filename);
			}
		//}
	});
}
