var swfu;
var actualplace;
var actualpage;
var actualmode = "";
function getPageSize(){
	var xScroll, yScroll;
	if (window.innerHeight && window.scrollMaxY) { 
		xScroll = document.body.scrollWidth;
		yScroll = window.innerHeight + window.scrollMaxY;
	} else if (document.body.scrollHeight > document.body.offsetHeight){ // all but Explorer Mac
		xScroll = document.body.scrollWidth;
		yScroll = document.body.scrollHeight;
	} else { // Explorer Mac...would also work in Explorer 6 Strict, Mozilla and Safari
		xScroll = document.body.offsetWidth;
		yScroll = document.body.offsetHeight;
	}
	var windowWidth, windowHeight;
	if (document.documentElement && document.documentElement.clientHeight) { // Explorer 6 Strict Mode
		windowWidth = document.documentElement.clientWidth;
		windowHeight = document.documentElement.clientHeight;
	} else if (document.body) { // other Explorers
		windowWidth = document.body.clientWidth;
		windowHeight = document.body.clientHeight;
	} 
	if(yScroll < windowHeight){
		pageHeight = windowHeight;
	} else { 
		pageHeight = yScroll;
	}
	if(xScroll < windowWidth){ 
		pageWidth = windowWidth;
	} else {
		pageWidth = xScroll;
	}
	var arrayPageSize = new Array(pageWidth,pageHeight,windowWidth,windowHeight) 
	return arrayPageSize;
}

function makePopup(on) {
	window.scrollTo(0,0);
	if(on) {
		var objBody = document.getElementsByTagName("body").item(0);
		if(!document.getElementById('overlay')) {
			ov = document.createElement('div');
			ov.setAttribute('id','overlay');
			ov.style.position = 'absolute';
			ov.style.top = '0';
			ov.style.left = '0';
			ov.style.zIndex = '1000';
			objBody.appendChild(ov);
			var ovEl = document.getElementById('overlay');
			winDim = getPageSize();
			ovEl.style.width = winDim[0] + 'px';
			ovEl.style.height = winDim[1] + 'px';
			ovEl.style.display = 'block';
			ovEl.style.visibility = 'visible';
			ov_box = document.createElement('div');
			ov_box.setAttribute('id','popup_dd');
			ov_box.setAttribute('class','boxPopup');
			objBody.appendChild(ov_box); 
			ov_box.style.position = 'absolute';
			var _left = parseInt(winDim[0]) / 2 - 300;
			var _top = 120;
			ov_box.style.top = _top +'px';
			ov_box.style.left = _left + 'px';
			ov_box.style.zIndex = '1001';
		}else{
			var ovEl = document.getElementById('overlay');
			winDim = getPageSize();
			ovEl.style.width = winDim[0] + 'px';
			ovEl.style.height = winDim[1] + 'px';
			ovEl.style.visibility = 'visible';
			ovEl.style.display = 'block';
		}
	}else {
		if(document.getElementById('overlay')) {
			document.getElementById('overlay').style.display = 'none';
			document.getElementById('overlay').style.visibility = 'visible';
		}
		if(document.getElementById('popup_dd')) {
			document.getElementById('popup_dd').style.display = 'none';
			document.getElementById('popup_dd').style.visibility = 'visible';
		}
	}
}

function initEditor(){
	tinyMCE.init({
		mode : "textareas",
		theme : "advanced",
		plugins : "safari,pagebreak,style,layer,table,save,advhr,advimage,advlink,inlinepopups,preview,media,searchreplace,contextmenu,paste,fullscreen,noneditable,visualchars,nonbreaking,template",

		// Theme options
		theme_advanced_buttons1 : "justifyleft,justifycenter,justifyright,justifyfull,styleselect,formatselect,fontselect,fontsizeselect,fullscreen",
		theme_advanced_buttons2 : "bold,italic,underline,strikethrough,|,cut,copy,paste,|,bullist,numlist,|,outdent,indent,blockquote,|,undo,redo,|,forecolor,backcolor,removeformat",
		theme_advanced_buttons3 : "",
		theme_advanced_buttons4 : "",
		theme_advanced_toolbar_location : "top",
		theme_advanced_toolbar_align : "left",
		theme_advanced_statusbar_location : "bottom",
		theme_advanced_resizing : true,
		template_external_list_url : "jscripts/tiny_mce/template_list.js",
		external_link_list_url : "jscripts/tiny_mce/link_list.js",
		external_image_list_url : "jscripts/tiny_mce/image_list.js",
		media_external_list_url : "jscripts/tiny_mce/media_list.js"
	});
}

function showImages(req)
{
	var jsonRaw = req.responseText;
	var prog = eval("(" + jsonRaw + ")");
	var length = prog['count'];
	var o = prog['res'];
	var h = prog['place'];
	var page = prog['page'];
	actualplace = prog['place'];
	actualpage = prog['page'];
	var html = "<table width='560' cellspacing='10'>";
	for(var i = 0; i < length; i=i+4){
		if((i+4)<length){
			var m1 = o['img'+i];
			var m2 = o['img'+(i+1)];
			var m3 = o['img'+(i+2)];
			var m4= o['img'+(i+3)];
			html += "<tr>";
			html += "<td valign='top'><a href='javascript:selectImage(\""+h+"\", \""+m1['id']+"\",\""+page+"\",\""+m1['path']+"\");' ><img src='"+m1['path']+"' width='110' /></a><br /><a onclick='deleteImage(\""+h+"\", \""+m1['id']+"\",\""+page+"\",\""+m1['path']+"\");' style='cursor:pointer;;color:red;'>usun</a></td>";
			html += "<td valign='top'><a href='javascript:selectImage(\""+h+"\", \""+m2['id']+"\",\""+page+"\",\""+m2['path']+"\");' ><img src='"+m2['path']+"' width='110' /></a><br /><a onclick='deleteImage(\""+h+"\", \""+m1['id']+"\",\""+page+"\",\""+m1['path']+"\");' style='cursor:pointer;;color:red;'>usun</a></td>";
			html += "<td valign='top'><a href='javascript:selectImage(\""+h+"\", \""+m3['id']+"\",\""+page+"\",\""+m3['path']+"\");' ><img src='"+m3['path']+"' width='110' /></a><br /><a onclick='deleteImage(\""+h+"\", \""+m1['id']+"\",\""+page+"\",\""+m1['path']+"\");' style='cursor:pointer;;color:red;'>usun</a></td>";
			html += "<td valign='top'><a href='javascript:selectImage(\""+h+"\", \""+m4['id']+"\",\""+page+"\",\""+m4['path']+"\");' ><img src='"+m4['path']+"' width='110' /></a><br/><a onclick='deleteImage(\""+h+"\", \""+m1['id']+"\",\""+page+"\",\""+m1['path']+"\");' style='cursor:pointer;color:red;'>usun</a></td>";
			html += "</tr><tr><td height='1' bgcolor='#999999' colspan='4'></td></tr>";
		}else{
			html += "<tr>";
			for(var j=i; j < length;j++){
				var m1 = o['img'+j];
				html += "<td valign='top'><a href='javascript:selectImage(\""+h+"\", \""+m1['id']+"\",\""+page+"\",\""+m1['path']+"\");' ><img src='"+m1['path']+"' width='110' /></a><br /><a onclick='deleteImage(\""+h+"\", \""+m1['id']+"\",\""+page+"\",\""+m1['path']+"\");' style='cursor:pointer;;color:red;'>usun</a></td>";
				if(j<(length-1)){
					//html += "<td width='1' bgcolor='#999999'></td>";
				}
			}
			html += "</tr>";
		}
	}
	html += "</tr></table>";
	makeImageEditor(html);
}

function showVideos(req)
{
	var jsonRaw = req.responseText;
	var prog = eval("(" + jsonRaw + ")");
	var length = prog['count'];
	var o = prog['res'];
	var h = prog['place'];
	var page = prog['page'];
	actualplace = prog['place'];
	actualpage = prog['page'];
	var html = "<table width='610'  border='1' cellpadding='0' cellspacing='0'><tr><td width='30' bgcolor='#666666' style='color:white;font-weight:bold;font-family:Verdana;font-size:12px;'>Id</td><td bgcolor='#666666'  style='color:white;font-weight:bold;font-family:Verdana;font-size:12px;' width='520'>Nazwa pliku</td><td width='60' bgcolor='#666666' style='color:white;font-weight:bold;font-family:Verdana;font-size:12px;'>Operacje</td></tr>";
	for(var i = 0; i < length; i++){
		var v = o['v'+i];
		html += ("<tr><td style='color:#666666;font-weight:bold;font-family:Verdana;font-size:11px;' >"+v['id']+"</td>"+"<td  style='color:#666666;font-weight:bold;font-family:Verdana;font-size:11px;'>"+v['path']+"</td>"+"<td  style='color:red;font-weight:bold;font-family:Verdana;font-size:11px;'><a style='cursor:pointer;' onclick='deleteVideo(\""+h+"\",\""+v['id']+"\",\""+page+"\",\""+v['path']+"\");'>usun</a>&nbsp;<a  style='cursor:pointer;' onclick='selectVideo(\""+h+"\",\""+v['id']+"\",\""+page+"\",\""+v['path']+"\")'>wybierz</a></td></tr>");
	}
	html += "</table>";
	makeVideoEditor(html);
}

function save(field,container,savebox,page,nr,editbox)
{
	var url = "save.php";
	var content = tinyMCE.get(field).getContent();
	new Ajax.Request( url, { method: "post",
		parameters: { 
			id: page,
			content: content,
			field: field,
			container: container,
			savebox: savebox,
			editbox: editbox,
			nr: nr
			},
		onComplete: checkResult });
}

function checkResult(req){
	
	var jsonRaw = req.responseText;
	var result = eval("(" + jsonRaw + ")");
	var userExist = result["result"];
	if(userExist == 1){
		hideEditor(result["field"],result["container"],result["savebox"],result["editbox"]);
	}else{
		alert('error');
	}
}



function showEditor(field,container,savebox,editbox){
	document.getElementById(savebox).style.visibility = "visible";
	document.getElementById(editbox).style.visibility = "hidden";
	tinyMCE.execCommand('mceRemoveControl',false,field);
	var inner = document.getElementById(container).innerHTML;
	var el = document.getElementById(container);
	inner = inner.replace(/</g,"&lt;");
	inner = inner.replace(/>/g,"&gt;");
	var html = "<textarea id='"+field+"' name='"+field+"' rows='15' cols='70' style='top:0px;width: 100%;background-color:#ff0000;'>"+inner+"</textarea>";
	
	el.innerHTML = html;
	tinyMCE.execCommand('mceAddControl',false,field);
	tinyMCE.get(field).show();
}
function hideEditor(field,container,savebox,editbox){
	document.getElementById(savebox).style.visibility = "hidden";
	document.getElementById(editbox).style.visibility = "visible";
	var html = tinyMCE.get(field,container).getContent();
	tinyMCE.execCommand('mceRemoveControl',false,field);
	var el = document.getElementById(container);
	el.innerHTML = html;
	
}
function showImageEditor(placeholder,page)
{
	var url = "getImages.php";
	new Ajax.Request( url, { method: "post", parameters:{
	imgh: placeholder,page:page}, onComplete: showImages });
}

function showVideoEditor(placeholder,page)
{
	var url = "getVideos.php";
	new Ajax.Request( url, { method: "post", parameters:{
	vh: placeholder,page:page}, onComplete: showVideos });
}

function selectImage(h,id,page,path)
{
	var url = "selectImage.php";
	new Ajax.Request( url, { method: "post", parameters:{
			placeholder: h,
			page: page, 
			path: path,
	id: id}, onComplete: selectImageRequest });
}

function selectVideo(h,id,page,path)
{
	var url = "selectVideo.php";
	new Ajax.Request( url, { method: "post", parameters:{
			placeholder: h,
			page: page, 
			path: path,
	id: id}, onComplete: selectVideoRequest });
}

function deleteImage(h,id,page,path)
{
	var url = "deleteImage.php";
	new Ajax.Request( url, { method: "post", parameters:{
			placeholder: h,
			page: page, 
			path: path,
	id: id}, onComplete: deleteImageRequest });
}

function deleteVideo(h,id,page,path)
{
	var url = "deleteVideo.php";
	new Ajax.Request( url, { method: "post", parameters:{
			placeholder: h,
			page: page, 
			path: path,
	id: id}, onComplete: deleteVideoRequest });
}
function selectImageRequest(req)
{
	var jsonRaw = req.responseText;
	var prog = eval("(" + jsonRaw + ")");
	var el = document.getElementById(prog['place']);
	if(el != undefined){
		el.innerHTML = prog['data'];
	}
	hideImageEditor();
}
function selectVideoRequest(req)
{
	var jsonRaw = req.responseText;
	var prog = eval("(" + jsonRaw + ")");
	var el = document.getElementById(prog['place']);
	
	if(el != undefined){
		el.innerHTML = prog['p'];
		var s1 = new SWFObject('mediaplayer/player.swf','player',prog['w'],prog['h'],'9');
		s1.addParam('allowfullscreen','true');
		s1.addParam('allowscriptaccess','always');
		s1.addParam('flashvars','file='+prog['path']+'');
		s1.write(prog['id']+'video');
	}
	hideVideoEditor();
}
function deleteImageRequest(req)
{
	var jsonRaw = req.responseText;
	var prog = eval("(" + jsonRaw + ")");
	hideImageEditor();
	showImageEditor(prog['place'],prog['page']);
}
function deleteVideoRequest(req)
{
	var jsonRaw = req.responseText;
	var prog = eval("(" + jsonRaw + ")");
	hideVideoEditor();
	showVideoEditor(prog['place'],prog['page']);
}
function initUpload(mode){
	var settings = null;
	actualmode = mode;
	var format = (mode=="images")?"*.TIF;*.EPS;*.PDF;*.JPG":"*.flv";
	var browser=navigator.appName;
	var prefixPath = "../";
	if(browser == "Microsoft Internet Explorer") prefixPath = "";
	if(FlashDetect.installed){
		if(FlashDetect.major!=10){
			settings = {
				flash_url : "upload/swfupload_f9.swf",
				upload_url: prefixPath+mode+"_upload.php",	// Relative to the SWF file
				post_params: {"PHPSESSID" : "<?php echo session_id(); ?>"},
				file_size_limit : "100 MB",
				file_types : format,
				file_types_description : "",
				file_upload_limit : 100,
				file_queue_limit : 0,
				custom_settings : {
					progressTarget : "fsUploadProgress",
					cancelButtonId : "btnCancel"
				},
				debug: false,

				// The event handler functions are defined in handlers.js
				file_queued_handler : fileQueued,
				file_queue_error_handler : fileQueueError,
				file_dialog_complete_handler : fileDialogComplete,
				upload_start_handler : uploadStart,
				upload_progress_handler : uploadProgress,
				upload_error_handler : uploadError,
				upload_success_handler : uploadSuccess,
				upload_complete_handler : uploadComplete,
				queue_complete_handler : queueComplete	// Queue plugin event
			};
			
		}else{
			settings = {
				flash_url : "upload/swfupload.swf",
				upload_url: prefixPath+mode+"_upload.php",	// Relative to the SWF file
				post_params: {"PHPSESSID" : "<?php echo session_id(); ?>"},
				file_size_limit : "100 MB",
				file_types : format,
				file_types_description : "opis",
				file_upload_limit : 100,
				file_queue_limit : 0,
				custom_settings : {
					progressTarget : "fsUploadProgress",
					cancelButtonId : "btnCancel"
				},
				debug: false,
				button_image_url: "",
				button_placeholder_id: "spanButtonPlaceholder",
				button_text: 'Przegladaj',
				button_width: 100,
				button_height: 20,
				// The event handler functions are defined in handlers.js
				file_queued_handler : fileQueued,
				file_queue_error_handler : fileQueueError,
				file_dialog_complete_handler : fileDialogComplete,
				upload_start_handler : uploadStart,
				upload_progress_handler : uploadProgress,
				upload_error_handler : uploadError,
				upload_success_handler : uploadSuccess,
				upload_complete_handler : uploadComplete
				//queue_complete_handler : queueComplete	// Queue plugin event
			};
			if(document.getElementById("v9") != undefined)document.getElementById("v9").style.visibility="hidden";
		}
	}
	swfu = new SWFUpload(settings);
}
function makeImageEditor(html)
{
	makePopup(true);
	document.getElementById('popup_dd').style.display='block';
	document.getElementById('popup_dd').style.visibility='visible';
	var form = "";
	form += "<table cellpadding='0' cellspacing='0'><tr><td width='610' height='25' bgcolor='white' ><table><tr><td width='580'><span style='color:#666666;font-family:Tahoma;font-size:12px;font-weight:bold;'>Kliknij na zdjecie zeby wybrac:</span></td><td width='30'><div style='position:relative;left:0px;'><table><tr><td><a style='cursor:pointer;' onmousedown='startDrag();' onmouseup='stopDrag();' ><span style='color:#666666;font-family:Tahoma;font-size:12px;font-weight:bold;'>Przesun</span></a></td><td><a style='cursor:pointer;' onclick='javascript:hideImageEditor();'><span style='color:#666666;font-family:Tahoma;font-size:12px;font-weight:bold;'>Zamknij</span></a></td></tr></table></div></td></tr><tr><td width='610' height='370' valign='top'  colspan='2'>";
	form += "<div id='scroll_clipper' style='position:relative;left:0px; width:610px; height: 370px; overflow:auto;scrollbar-arrow-color: #000000;scrollbar-base-color: #ffffff;scrollbar-track-color: #ffffff;scrollbar-highlight-color:#ffffff;scrollbar-shadow-color:#ffffff;'>";
	form += html;
	
	form +="</div></td></tr><tr><td width='610' colspan='2' height='1' bgcolor='#666666'></td></tr><tr><td width='610' colspan='2'>";
	form +="<fieldset  id='fsUploadProgress'></fieldset><div id='divStatus'></div>";
	form +="<div><div id='spanButtonPlaceholder'></div>";
	var visibility = "visible";
	if(FlashDetect.major==10){
		visibility = "hidden";
	}
	form += "<div id='v9' style='visibility:"+visibility+"'>";
	form +="<input type='button' value='Szukaj...' onclick='swfu.selectFiles()' style='font-size: 8pt;' />";
	form +="<input id='btnCancel' type='button' value='przerwij' onclick='swfu.cancelQueue();' disabled='disabled' style='font-size: 8pt;' />";
	form +="</div>";

	form +="</div>";
	form +="</td></tr></table>";
	document.getElementById('popup_dd').innerHTML = form;
	initUpload('images');
	
}


function makeVideoEditor(html)
{
	makePopup(true);
	document.getElementById('popup_dd').style.display='block';
	document.getElementById('popup_dd').style.visibility='visible';
	var form = "";
	form += "<table cellpadding='0' cellspacing='0' ><tr><td width='610' height='25' bgcolor='white'><table><tr><td width='580'><span style='color:#666666;font-family:Tahoma;font-size:12px;font-weight:bold;'>Wybierz film FLV:</span></td><td width='30'><div style='position:relative;left:0px;'><table><tr><td><a style='cursor:pointer;' onmousedown='startDrag();' onmouseup='stopDrag();' ><span style='color:#666666;font-family:Tahoma;font-size:12px;font-weight:bold;'>Przesun</span></a></td><td><a style='cursor:pointer;' onclick='javascript:hideVideoEditor();'><span style='color:#666666;font-family:Tahoma;font-size:12px;font-weight:bold;'>Zamknij</span></a></td></tr></table></div></td></tr><tr><td width='610' height='375' valign='top'  colspan='2'>";
	form += "<div id='scroll_clipper' style='position:relative;left:0px; width:610px; height: 375px; overflow:auto;scrollbar-arrow-color: #000000;scrollbar-base-color: #ffffff;scrollbar-track-color: #ffffff;scrollbar-highlight-color:#ffffff;scrollbar-shadow-color:#ffffff;'>";
	form += html;
	
	form +="</div></td></tr><tr><td width='610' colspan='2' height='1' bgcolor='#666666'></td></tr><tr><td width='610' colspan='2'>";
	form +="<fieldset  id='fsUploadProgress'></fieldset><div id='divStatus'></div>";
	form +="<div><div id='spanButtonPlaceholder'></div>";
	var visibility = "visible";
	if(FlashDetect.major==10){
		visibility = "hidden";
	}
	form += "<div id='v9' style='visibility:"+visibility+"'>";
	form +="<input type='button' value='Szukaj...' onclick='swfu.selectFiles()' style='font-size: 8pt;' />";
	form +="<input id='btnCancel' type='button' value='przerwij' onclick='swfu.cancelQueue();' disabled='disabled' style='font-size: 8pt;' /><br />";
	form +="</div>";

	form +="</div>";
	form +="</td></tr></table>";
	document.getElementById('popup_dd').innerHTML = form;
	initUpload('videos');
	
}

function startDrag(){
	Drag.init(document.getElementById('popup_dd'));
}
function stopDrag(){
	document.getElementById('popup_dd').onmousedown = null;
	document.getElementById('popup_dd').onmouseup = null;
	Drag.end();
}
function hideImageEditor()
{
	makePopup(false);
}
function hideVideoEditor()
{
	makePopup(false);
}
