function updateauto(){
tinymce.selectedInstance.execCommand('mceAutoResize'); //Update autoresize
}
$(document).ready(function() {


		var $scrollingDiv = $(".popupbox");
 
		$(window).scroll(function(){			
			$scrollingDiv
				.stop()
				.animate({"marginTop": ($(window).scrollTop() + 30) + "px"}, "slow" );			
		});


//editorhoverinit();
$(".closebutton").click(function(){
closeAll();
});
$(document).keyup(function(e) {
  if (e.keyCode == 27) {closeAll()  }   // esc  
});

gtextcancel = "Avbryt";
gtextsave = "Spara";
gtextpic = "Ladda upp bild";
gtexttable = "Infoga tabell";

$('#editortablecancel').click(function() {
$('#tableinserterholder').html('<table id="uniqtabledit" border="1"><tr class="uniqt"><td class="uniqt"></td><td class="uniqt"></td></tr><tr class="uniqt"><td class="uniqt"></td><td class="uniqt"></td></tr></table>');
//editorhoverinit();
closeAll();
});


$('#tbordercolor').change(function(){
bcolor = $('#tbordercolor').val();
if(bcolor==1){
$('.uniqt').css('border','1px solid #999');
$('#uniqtabledit').css('border','1px solid #999');
}
if(bcolor==2){
$('.uniqt').css('border','none');
$('#uniqtabledit').css('border','none');
}
});
$('#editortableinsok').click(function() {

$('.uniqtinput').blur();
$("#uniqtabledit").each(function(i, t) {
   $tds = $("td", t);
   $trs = $("tr", t);
   num = $tds.length;
   num2 = $trs.length;
   numonrow = num/num2;
   equalpercent = 100/numonrow;
   $tds.css("width", equalpercent+"%");
});

 $('#tableinserterholder #uniqtabledit').css('width','100%');
 $('#tableinserterholder #uniqtabledit').addClass('uniqtabledit2');
 $('#tableinserterholder #uniqtabledit').removeAttr('id');

var newContent = $('#tableinserterholder').html()+'<p></p>'; // your HTML to be inserted
tinyMCE.execCommand('mceBeginUndoLevel'); // set an undo point
tinyMCE.selectedInstance.execCommand('mceInsertContent', false, newContent); // insert content at cursor position/selection
tinyMCE.execCommand('mceEndUndoLevel'); // set an undo point
$('#tableinserterholder').html('<table id="uniqtabledit" style="width: 100%;"><tr class="uniqt"><td class="uniqt"></td><td class="uniqt"></td></tr><tr class="uniqt"><td class="uniqt"></td><td class="uniqt"></td></tr></table>');
$('#editorfolder').change();
editorreaddirs();
closeAll();
tinyMCE.execCommand('mceAutoResize'); //Update autoresize
});


$('.uniqcol').click(function() {
$('#uniqtabledit tr').append('<td class="uniqt"></td>');
var num;
var $tds;
$("#uniqtabledit").each(function(i, t) {
   $tds = $("td", t);
   $trs = $("tr", t);
   num = $tds.length;
   num2 = $trs.length;
   numonrow = num/num2;
   equalpercent = 100/numonrow;
   $tds.css("width", equalpercent+"%");
});
});
$('.uniqrow').click(function() {

$("#uniqtabledit").each(function(i, t) {
   $tds = $("td", t);
   $trs = $("tr", t);
   num = $tds.length;
   num2 = $trs.length;
   numonrow = num/num2;
   equalpercent = 100/numonrow;
});

i = 0;
therows = '';
while (i < numonrow){
therows = therows+'<td class="uniqt"></td>';
i++;
}
$('#uniqtabledit').append('<tr class="uniqt">'+therows+'</tr>');
});

$('.uniqrowm').click(function() {
amounttds = $('#uniqtabledit tr td:last-child').size();
if(amounttds>1){
$('#uniqtabledit tr:last').remove();
}
});

$('.uniqcolm').click(function() {
amounttds = $('#uniqtabledit tr:first td').size();

if(amounttds>1){
$('#uniqtabledit tr td:last-child').remove();
}
});

$('#editorcontinue2').click(function() {
//selarray

if(selarray.length>0){
$('#editorstep1').hide();
$('#editorstep2').slideDown(300);


$('#editorshowname').html("\""+selarray[0].split(",")[0]+"\" (1/"+selarray.length+")");

$('.editortitlehold').html("LADDA UPP BILD  - STEG 2");
theurl = selarray[1];
 
}else{
//empty
}
 
 
});
imageat = 0;
$('#thesubmit').click(function() {
$(this).attr('disabled', 'disabled').val("Laddar ...");
$('.loadholder').show();

//theimage selarray theurl
realurl = selarray[imageat].split(",")[1];
thesize = $('[name="editorisize"]:checked').val();
thealign = $('[name="editorialign"]:checked').val();
thealt = $('#editorialt').val();
watermark = $('#editorwater').val();
edtags = $('#editortagshid').val();

insertalign='align="none"';stylec="";
if(thealign==1){insertalign='align="left"'}
if(thealign==2){insertalign='align="center"';stylec = "text-align: center;"}
if(thealign==3){insertalign='align="right"'}
insertalt = 'alt="'+thealt+'"';


   $.ajax({
  type: "POST",
  url: "fileditorhandler.php?type=imgresize",
  data: "thesize="+thesize+"&thealign="+thealign+"&thealt="+thealt+"&theimage="+realurl+"&thewatermark="+watermark,
  cache: false,
  success: function(data){
var newContent = '<p style="'+stylec+'"><img class="blockimg" src="'+data+'" '+insertalign+' '+insertalt+' fbtags="'+edtags+'" /></p><p></p>'; // your HTML to be inserted
tinyMCE.execCommand('mceBeginUndoLevel'); // set an undo point
tinyMCE.selectedInstance.execCommand('mceInsertContent', false, newContent); // insert content at cursor position/selection
tinyMCE.execCommand('mceEndUndoLevel'); // set an undo point


setTimeout("updateauto()",500);
imageat++;


$('#thesubmit').removeAttr('disabled').val("Infoga");
$('.loadholder').hide();


if (imageat==selarray.length){
t=$('.editoritem');
selarray = [];imageat=0; $('#edtexthelp').show();estarted =0;
$('.editortheimage:first',t).css({"border":"none","margin":"5px 0 0 5px"});
$('.editortextbox:first',t).css({"font-weight":"normal","background":"transparent"});
t.removeClass('eiselected');
closeAll();
}else{
displayat = imageat+1;
$('#editorstep2').hide().slideDown(300);
$('#editorshowname').html("\""+selarray[imageat].split(",")[0]+"\" ("+displayat+"/"+selarray.length+")");
}

  }
  });
  
  


});



$('#addf').click(function() {
   $.ajax({
  type: "POST",
  url: "fileditorhandler.php?type=createdir",
  data: "mf="+$('#editormfinput').val(),
  cache: false,
  success: function(data){
$("#editorfolder option[selected]").removeAttr("selected");
$('#editorfolder').append(data);

editorreaddirs();
  }
  });
});

$('#editorfolder').change(function() {
editorreaddirs();
});


i=0;estarted = 0;
$('.editoritem').each(function(index) {
i = Number(index)+1;
});


$('#image_upload').uploadify({
    'uploader'  : 'uploadify/uploadify.swf',
    'script'    : 'uploadify/uploadify.php',
    'cancelImg' : 'uploadify/cancel.png',
	'scriptData': {'session': '1','dirr':'root'},
    'auto'      : true,
	'multi' : true,
	'removeCompleted' : true,
	'fileExt'     : '*.jpg;*.png;*.jpeg',
	'fileDesc'    : 'Bildfil (.JPG, .GIF, .PNG)',
	'buttonText' : 'Ladda upp bild',
	'simUploadLimit' : 1,
	'queueSizeLimit' : 5,
	'queueID'        : 'editorqueue',
	'onComplete'  : function(event, ID, fileObj, response, data) {
	var splitresponse = response.split(",");
	var unixpath = splitresponse[0];
	nameonly = splitresponse[1];

	dateonly = splitresponse[2];
	sizeonly = splitresponse[3];
	shortnamer = splitresponse[4];
	
	
	string = shortnamer;
	if(string.length > 16) {
    string1 = string.substring(0,15)+"<br />";
    string2 = string.substring(15);
	if(string2.length > 16) {
	string2 = string2.substring(0,15)+"...";
	}
	fullnameonly = string1+string2;
}else{
fullnameonly = string;
}
//Insert to array
selarray.push(shortnamer+','+unixpath);


	 $("#editorimages").prepend('<div id="ei'+i+'" class="editoritem eiselected" style="display: none;">'+
	 '<input type="hidden" id="hidimg'+i+'" value="'+unixpath+'" />'+
	 '<input type="hidden" id="hidimgname'+i+'" value="'+shortnamer+'" />'+
'<div class="editoritem1"><div class="editortheimage" style="border: 2px dotted #333; margin: 3px 0 0 3px; background: transparent url(timthumb.php?h=50&w=50&src='+unixpath+') no-repeat top left"></div>'+
'<div class="editortextbox" style="font-weight: bold; background: transparent url(img/icons/eiselected.png) no-repeat center right;">'+fullnameonly+'</div>'+
'</div><div class="editoritem2"><div class="editortextbox">'+sizeonly+'</div>'+
'</div><div class="editoritem3"><div class="editortextbox">'+dateonly+'</div></div><div class="editoritem4"></div></div>');
$("#ei"+i).slideDown(300);
//editorhoverinit();



	  i++;
},
'onSelect'    : function(event,ID,fileObj) {
	thedir = $('#editorfolder').val();
	
	$('#image_upload').uploadifySettings("scriptData", {'dirr': thedir });
    },
	'onAllComplete' : function(event,data) {
$('#editorstep1').hide();
$('#editorstep2').slideDown(300);


$('#editorshowname').html("\""+selarray[0].split(",")[0]+"\" (1/"+selarray.length+")");

$('.editortitlehold').html("ADD IMAGE - STEP 2");
theurl = selarray[1];    
    },
	 'onOpen'      : function(event,ID,fileObj) {
	 if(estarted==0){
	 $('#edtexthelp').hide();estarted=1;
	 }
      
    }
  });
  });

  
  //Use live instead of handlers.
  
 $('.editoritem1,.editoritem2,.editoritem3').live("click",editoreditclick);
 $('.editoritem4').live("click",editorfdela);
 $('.editorslideshower').live("click",showeditorhandlerc);
 
 $(".editoritem1,.editoritem2,.editoritem3").live("mouseover",editoredithandler);
 $(".editoritem1,.editoritem2,.editoritem3").live("mouseout",editoredithandler2);
 
 $(".editoritem4").live("mouseover", editorfdelh1);
 $(".editoritem4").live("mouseout", editorfdelh2);
 
 

function showeditorhandlerc(){
manbearpig = $(this).parent('.editorslidehide').attr("class");
mode = $(this).parent('.editorslidehide').attr("mode");
showeditor('.'+manbearpig,mode);
}


function editoredithandler(){$(this).parent('.editoritem').css("background-color","#e5e5e5")}
function editoredithandler2(){$(this).parent('.editoritem').css("background-color","#efefef")}

function editorfdelh1(){
$(this).css("background","transparent url('img/icons/close16h.png') no-repeat center center")
$(this).parent('.editoritem').css("background","#e5e5e5 url(img/icons/delitemh.png) repeat-x top left")
}
function editorfdelh2(){
$(this).css("background","transparent url('img/icons/close16.png') no-repeat center center")
$(this).parent('.editoritem').css("background","#efefef")
}
function editorfdela(){
theid = $(this).parent('.editoritem').attr("id").replace("ei","");
emainitem = $(this).parent('.editoritem');
thename = $('#hidimgname'+theid).val();
theimg = $('#hidimg'+theid).val();

var answer = confirm("Radera vald bild? ("+thename+")");
if (answer){
   $.ajax({
  type: "POST",
  url: "fileditorhandler.php?type=deletefile",
  data: "df="+theimg,
  cache: false,
  success: function(data){
  emainitem.slideUp(300);
}
  });
  }
 
 
}


selarray = new Array(); 

function editoreditclick(){
eallselects = $('#eallselects');
emainitem = $(this).parent('.editoritem');
theid = emainitem.attr("id").replace("ei","");
thename = $('#hidimgname'+theid).val();
theimg = $('#hidimg'+theid).val();


if(emainitem.hasClass("eiselected")){
emainitem.removeClass("eiselected");
$('.editoritem1 .editortheimage',emainitem).css({"border":"none","margin":"5px 0 0 5px"});
$('.editoritem1 .editortextbox',emainitem).css({"font-weight":"normal","background":"transparent"});
namepos = selarray.findIndex(thename+','+theimg);
selarray.splice(namepos,1);

atemper = "";
for (counter=0; counter<selarray.length; counter++){thesplit = selarray[counter].split(",");atemper = atemper+" "+thesplit[0];}
eallselects.html(atemper);
$('#eallselectscount').html('['+selarray.length+'/5]');
}else{
if(selarray.length<5){
$(emainitem).addClass("eiselected");
$('.editoritem1 .editortheimage',emainitem).css({"border":"2px dotted #333","margin":"3px 0 0 3px"});
$('.editoritem1 .editortextbox',emainitem).css({"font-weight":"bold","background":"transparent url('img/icons/eiselected.png') no-repeat center right"});
selarray.push(thename+','+theimg);
atemper = "";
for (counter=0; counter<selarray.length; counter++){thesplit = selarray[counter].split(",");atemper = atemper+" "+thesplit[0];}
eallselects.html(atemper);
$('#eallselectscount').html('['+selarray.length+'/5]');
}else{
eallselects.hide();
eallselects.fadeIn(500);

}
}
}





function editorreaddirs(){

   $.ajax({
  type: "POST",
  url: "fileditorhandler.php?type=readdirs",
  data: "wf="+$('#editorfolder').val(),
  cache: false,
  success: function(data){
$('#editorimages').html(data);
//editorhoverinit();
fullit = new Array();
$('.editoritem').each(function(i, t) {
theimgname = $('.hidimgname',t).val();
theimg = $('.hidimg',t).val();
theid = $(t).attr("id").replace("ei","");

iit = theimgname+','+theimg;

if(iit === selarray[selarray.findIndex(iit)]){
$(t).addClass("eiselected");
$('.editortheimage:first',t).css({"border":"2px dotted #333","margin":"3px 0 0 3px"});
$('.editortextbox:first',t).css({"font-weight":"bold","background":"transparent url('img/icons/eiselected.png') no-repeat center right"});
}
});
  
  
}
  });
  
  
  
  }
  
Array.prototype.findIndex = function(value){
for (var i=0; i < this.length; i++) {
// use === to check for Matches. ie., identical (===), ;
if (this[i] === value) {
return i;
}
}
return false;
};
function showeditor(id){

if(id==""){
maindiv = $('.editorslidehide');
}else{
maindiv = $(id);
}
$('.editorslideshower').remove();
//editorhoverinit();
$('.editorslidehide').animate({width: beforewidth}, 1800, "easeInOutQuart", function(){
$('.editorcontent').fadeOut(300);
$('.editorslidehide').animate({
    height: beforeheight
  }, 200, "linear",function(){

  $('.editorslidehide').css('height','auto');

  
  
  
  
  });
  
  
});


}

function hideeditor(id){

if(id==""){
maindiv = $('.editorslidehide');
}else{
maindiv = $(id);
}
//beforeheight = $('#mceEditorfoot_parent').css("height");
beforewidth = maindiv.css("width");
  maindiv.animate({
    height: "29px"
  }, 200, "linear", function(){
 $('.editorcontent').fadeIn(500);
  maindiv.animate({width: "hide"}, 1800, "easeInOutQuart", function(){
  maindiv.prepend('<div class="editorslideshower"></div>');

  maindiv.css("width","29px").fadeIn(300);
  //editorhoverinit();
  
  });
  
  
  });
}

function closeAll(){
$('.popupselector').fadeOut(300);
$('#editorstep1').show();
$('#editorstep2').hide();
$('#imageditor').hide();
$("#tableditor").hide();
$("#templateditor").hide();
$('.editorpad').find(':input').each(function() {
    switch(this.type) {
            case 'text':
            case 'textarea':
                $(this).val('');
                break;
        }
});
$('#editortags').tagit('removeAll');
$('.editortitlehold').html("LADDA UPP BILD  - STEG 1");
}




  
