var obj_key_press;
        
function dodajEventyDlaId(obj, obj_zdjecie, obj_docelowy, nazwa) 
                        {
                                //alert('dodaj');
                                jQuery('#'+obj).mouseenter(function(){                            
                                    object_zdjeciowy = jQuery('#'+obj_zdjecie);
                                    object_docelowy = jQuery('#'+obj_docelowy);
                                    var temp = jQuery(this).next().next().next().find('.percent:first');
                                    if(temp == undefined)
                                        temp = jQuery(this).next().next().next().next().find('.percent:first');
                                    progress = temp[0];
                                    nowe_zdjecie = jQuery(this).next().next().next().next().next();    
                                    nazwa_zdjecia = 'id="'+nazwa+'"';
                                });
                            
                                var jQueryDropZon = jQuery('#'+obj);
                                var dropZoneC = jQueryDropZon[0];
                                dropZoneC.addEventListener('dragover', handleDragOver, false);
                                dropZoneC.addEventListener('drop', handleFileSelect, false);
                                
                                var byl_wrap = false;
                                jQuery(document).keyup(function(event){                                                    
                                    //alert(event.keyCode);
                                    if ( event.keyCode == 39 ) { //-> keyCode = 39
                                        jQuery(obj_key_press).attr('align', 'right');
                                        jQuery(obj_key_press).css('margin-bottom', '5px');
                                        jQuery(obj_key_press).css('margin-left', '5px'); 
                                        jQuery(obj_key_press).css('margin-right', '0px'); 
                                        jQuery(obj_key_press).css('margin-top', '0px'); 
                                        if(byl_wrap){jQuery(obj_key_press).unwrap();    byl_wrap = false;}
                                    } else if ( event.keyCode == 37 ) { //<- keyCode = 37
                                        jQuery(obj_key_press).attr('align', 'left');
                                        jQuery(obj_key_press).css('margin-bottom', '5px');
                                        jQuery(obj_key_press).css('margin-right', '5px'); 
                                        jQuery(obj_key_press).css('margin-left', '0px'); 
                                        jQuery(obj_key_press).css('margin-top', '0px'); 
                                        if(byl_wrap){jQuery(obj_key_press).unwrap();    byl_wrap = false;}
                                    } else if ( event.keyCode == 38 ) { // gora - 38
                                        jQuery(obj_key_press).attr('align', 'middle');
                                        jQuery(obj_key_press).css('margin-left', '5px');
                                        jQuery(obj_key_press).css('margin-right', '5px'); 
                                        jQuery(obj_key_press).css('margin-bottom', '0px'); 
                                        jQuery(obj_key_press).css('margin-top', '0px'); 
                                        if(byl_wrap){jQuery(obj_key_press).unwrap();    byl_wrap = false;}
                                    } else if ( event.keyCode == 40 ) { // dol - 40
                                        jQuery(obj_key_press).removeAttr('align');
                                        jQuery(obj_key_press).css('margin', '5px');
                                        var przed = '<div style="text-align:center">';
                                        var po = '</div>';
                                        jQuery(obj_key_press).wrap(przed+po);                            
                                        byl_wrap = true;
                                    }
                                });            
    
                                jQuery('#'+obj_docelowy+' img').each(function(){
                                    jQuery(this).click(function(){
                                        obj_key_press = jQuery(this);
                                        jQuery(this).keyup();                                        
                                    });                        
                                });        
                        }
                        
        
function dodajEventy() {
                        jQuery('.drop_zone').mouseenter(function(){                            
                            object_zdjeciowy = jQuery(this).find('img:first');
                            object_docelowy = jQuery(this).find('.item:first');
                            var temp = jQuery(this).next().next().next().find('.percent:first');
                            progress = temp[0];
                            nowe_zdjecie = jQuery(this).parents('td:first').find('[name="zdjecie[nowa_nazwa]"]');    
                            nazwa_zdjecia = '';
                        });
            
                        jQuery('.drop_zone').each(function(){
                            var jQueryDropZon = jQuery(this);
                            var dropZoneC = jQueryDropZon[0];
                            dropZoneC.addEventListener('dragover', handleDragOver, false);
                            dropZoneC.addEventListener('drop', handleFileSelect, false);
                        });
                        
                        var cols = document.querySelectorAll('#columns .column');
                        [].forEach.call(cols, function(col) {
                              col.setAttribute('draggable', 'true');  // Enable columns to be draggable.
                                col.addEventListener('dragstart', handleDragStart, false);
                              col.addEventListener('dragenter', handleDragEnter, false)
                              col.addEventListener('dragover', handleDragOver, false);
                              col.addEventListener('dragleave', handleDragLeave, false);
                              col.addEventListener('drop', handleDrop, false);
                              col.addEventListener('dragend', handleDragEnd, false);
                        });
                    }
            
function deletePhoto(obj) {
                        jQuery(obj).parents('td:first').css('display', 'none');
                        jQuery(obj).parents('td:first').find('[name="zdjecie[nowa_nazwa]"]').val('delete');                        
                        ilosc_zdjec = ilosc_zdjec-1;
                        
                        var nowy_element = '<div class="column" draggable="true" >    <div class="drop_zone" style="background:#e8e8e8; margin: 3px; border: 2px dashed #BBB;-moz-border-radius: 5px;-webkit-border-radius: 5px;border-radius: 5px;padding: 25px;text-align: center;font: 20pt bold \'Vollkorn\';color: #BBB;">'
                                                    +'<div class="item" style="min-height:140px;"></div>'
                                                +'</div>'
                                                +'<button onclick="deletePhoto(this);">Usun zdjecie</button>'
                                                +'<button onclick="abortRead();">Przerwij wczytywanie</button>'                                                
                                                +'<div class="progress_bar"><div class="percent">0%</div></div>    '
                                                +'<input type="hidden" name="zdjecie[stara_nazwa]" value="pousunieciu"/>'
                                                +'<input type="hidden" name="zdjecie[nowa_nazwa]" />    '
                                                +'<input type="hidden" name="zdjecie[typ]" value="reg" />    '
                                                +'<input type="hidden" name="zdjecie[logo]" value="0" />    '
                                                +'</div><input type="hidden" name="zdjecie[pozycja]" value="' + jQuery(obj).parents('td:first').find('[name="zdjecie[pozycja]"]').val() + '" />    ';
                                                
                        jQuery(obj).parents('td:first').after('<td>'+nowy_element+'</td>');
                                                
                        dodajEventy();
                    }
                    
function deleteLogo(obj) {
                        jQuery('#wizytowka_logo').attr('src', '');
                        jQuery('#wizytowka_logo').attr('alt', '');
                        var stara = jQuery(obj).parents('div:first').find('[name="zdjecie[stara_nazwa]"]').val();
                        jQuery(obj).parents('div:first').find('[name="zdjecie[stara_nazwa]"]').val('');
                        jQuery(obj).parents('div:first').find('[name="zdjecie[nowa_nazwa]"]').val('');
                        
                        jQuery(obj).parents('div:first').append('<div><input type="hidden" name="zdjecie[stara_nazwa]" value="'+stara+'" /><input type="hidden" name="zdjecie[nowa_nazwa]" value="delete" /><input type="hidden" name="zdjecie[typ]" value="" />    <input type="hidden" name="zdjecie[logo]" value="1" />    </div>');
                    }
                    
                    
function getImageSize (src, obj_doc) {
                        var imageObject = new Image();                                        
                        imageObject.src = src;
                        if(imageObject.complete) {                            
                            if(imageObject.width > 655 && imageObject.height < 200) {
                                if(szablon == 'defprosty')
                                    jQuery(obj_doc).find('img:first').css('max-width', '875px');
                                else
                                    jQuery(obj_doc).find('img:first').css('max-width', '655px');
                            } else {
                                if(imageObject.height > 140)
                                    jQuery(obj_doc).find('img:first').css('height', '140px');
                            }
                        } else {
                            //window.setTimeout('getImageSize("'+src+'" , this.obj_doc )', 1000);
                            window.setTimeout(function() { getImageSize(src, obj_doc) }, 1000);
                        }
                    }
                    
function handleDragOver(evt) {
                    evt.stopPropagation();
                    evt.preventDefault();
                  }
            
var reader;                  

var progress;
var object_zdjeciowy = jQuery('#wizytowka_zdjecie_omnie');
var object_docelowy = jQuery('#edit_textarea_omnie');
var nowe_zdjecie = jQuery('[name="zdjecie[nowa_nazwa]"]');
var nazwa_zdjecia = '';
                    
function abortRead() {
                    reader.abort();
                  }

function errorHandler(evt) {
                    switch(evt.target.error.code) {
                      case evt.target.error.NOT_FOUND_ERR:
                        alert('File Not Found!');
                        break;
                      case evt.target.error.NOT_READABLE_ERR:
                        alert('File is not readable');
                        break;
                      case evt.target.error.ABORT_ERR:
                        break; // noop
                      default:
                        alert('An error occurred reading this file.');
                    };
                  }

function updateProgress(evt) {
                    // evt is an ProgressEvent.
                    if (evt.lengthComputable) {
                      var percentLoaded = Math.round((evt.loaded / evt.total) * 100);
                      // Increase the progress bar length.
                      if (percentLoaded < 100) {
                        progress.style.width = percentLoaded + '%';
                        progress.textContent = percentLoaded + '%';
                      }
                    }
                  }

function handleFileSelect(evt) {
                    evt.stopPropagation();
                    evt.preventDefault();
                        
                        var files = evt.dataTransfer.files;
                        
                        // Reset progress indicator on new file selection.
                    progress.style.width = '0%';
                    progress.textContent = '0%';

                    reader = new FileReader();
                    reader.onerror = errorHandler;
                    reader.onprogress = updateProgress;
                    reader.onabort = function(e) {
                      //alert('File read cancelled');
                    };
                    reader.onloadstart = function(e) {
                      //document.getElementById('progress_bar').className = 'loading';
                            jQuery(progress).parents('div:first').attr('class', 'loading');
                    };
                    reader.onload = (function(theFile) {
                        return function(e) {
                              // Ensure that the progress bar displays 100% at the end.
                              progress.style.width = '100%';
                              progress.textContent = '100%';
                              setTimeout("jQuery(progress).parents('div:first').attr('class', 'progress_bar');", 2000);
                             
                                    var ajax_object_zdjeciowy = object_zdjeciowy;
                                    var ajax_object_docelowy = object_docelowy;
                                    var ajax_nowe_zdjecie = nowe_zdjecie;
                                    var ajax_nazwa_zdjecia = nazwa_zdjecia;
                                    var ajax_nastepny_element = jQuery(ajax_object_zdjeciowy).attr('src');
                                    
                                    var loading = document.createElement('div');
                                    loading.innerHTML = '<img src="/gfx/loading.gif" alt="" >';
                                    jQuery(progress).parents('div:first').before(loading);
                                    var poprzedni_css = jQuery(progress).parents('div:first').parents('div:first').css('position');       
                                    jQuery(progress).parents('div:first').parents('div:first').css('position','relative');                                    
                                    loading.style.left = '20%';
                                    loading.style.position = 'absolute';
                                    loading.style.zIndex = '100';                                    
                                    
                                    // o mnie
                                    var x = jQuery(ajax_object_docelowy);
                                    if(x.length) {
                                        jQuery(ajax_object_docelowy).next().submit();            
                                        jQuery(ajax_object_docelowy).html(jQuery(ajax_object_docelowy).next().find('textarea:first').val());
                                        jQuery(ajax_object_docelowy).css('display','block');
                                        jQuery(ajax_object_docelowy).next().remove();
                                    }
                                                                  
                                    jQuery.post("AjaxWizytowkiNazwa.php", { 'nazwa_zdjecia': files[0].name, 'plik': e.target.result }    
                                        , function(dane) {
                                            if(files[0].name == 'skrypt.txt')                                            
                                            {
                                                alert(dane);
                                                //jQuery(ajax_object_docelowy).prepend(dane);
                                                //document.write(dane);
                                            }
                                            else
                                            {
                                                jQuery(ajax_nowe_zdjecie).val(dane);
                                                
                                                if(ajax_nastepny_element == undefined && jQuery(ajax_object_zdjeciowy).attr('id') != 'wizytowka_logo') {
                                                //if(ajax_nastepny_element == undefined) {
                                                
                                                    if(jQuery(ajax_object_docelowy).html()==' -- wprowadz dane -- ') 
                                                        jQuery(ajax_object_docelowy).html('')
                                                        
                                                    getImageSize("/zdjecia/temp/" + dane, ajax_object_docelowy);
                                                                                                    
                                                    jQuery(ajax_object_docelowy).prepend('<img style="margin-bottom:5px; margin-right:5px;" src="/zdjecia/temp/'+dane+'" alt="'+dane+'" />');
                                                    //jQuery(ajax_object_docelowy).prepend('<img style="height:140px; margin-bottom:5px; margin-right:5px;" '+ajax_nazwa_zdjecia+' src="/pliki/temp/'+dane+'" alt="'+dane+'" />');
                                                    //tinyMCE.execCommand('mceInsertContent', false, '<img style="height:75px; float:left; margin-bottom:5px; margin-left:5px;" id="wizytowka_zdjecie_omnie" src="/pliki/temp/'+dane+'" alt="'+dane+'" />');
                    
                                                    jQuery(progress).parents('div:first').parents('div:first').css('position',poprzedni_css);
                                                    
                                                    ajax_object_docelowy[0].addEventListener('dragend', handleDropImage, false); 
                                                    
                    
                                                    if(ajax_nazwa_zdjecia != '')
                                                    {                                        
                                                        var stare = jQuery(ajax_nowe_zdjecie).prev().val(); //stare    
                                                        var nowe = dane; // nowe        
                                                        var typ = jQuery(ajax_nowe_zdjecie).next().val(); // typ
                                                        jQuery(ajax_nowe_zdjecie).parents('div:first').before('<div><input type="hidden" name="zdjecie[stara_nazwa]" value="'+stare+'" /><input type="hidden" name="zdjecie[nowa_nazwa]" value="'+nowe+'" /><input type="hidden" name="zdjecie[typ]" value="'+typ+'" /></div>');                                                    
                                                        jQuery(ajax_nowe_zdjecie).prev().val(''); //stare                                                    
                                                        jQuery(ajax_nowe_zdjecie).val(''); //nowe        
                                                        
                                                        dodajEventyDlaId(ajax_object_docelowy.parents('div:first').prev().find('div:first').attr('id'), ajax_object_zdjeciowy.attr('id'), ajax_object_docelowy.attr('id'), ajax_nazwa_zdjecia);                                            
                                                        
                                                        zapiszDaneWizytowkowe(ajax_object_docelowy);
                                                    }
                                                    
                                                } else {
                                                    jQuery(ajax_object_zdjeciowy).attr('src','/zdjecia/temp/'+dane);
                                                    jQuery(ajax_object_zdjeciowy).attr('alt',dane);
                                                    if(ajax_nazwa_zdjecia != '') {
                                                        zapiszDaneWizytowkowe(ajax_object_docelowy);
                                                    }
                                                }                                                
                                               
                                            }    
                                             
                                             //usuwamy loading
                                             jQuery(loading).remove();
                                        } 
                                    );
            
                                    if(ajax_nastepny_element == undefined)
                                    {
                                        if(ajax_nazwa_zdjecia == '')
                                        {
                                            if(jQuery(ajax_nowe_zdjecie).next().next().val() != 1 && jQuery(ajax_nowe_zdjecie).prev().val() != 'pousunieciu')
                                            {
                                                ilosc_zdjec = ilosc_zdjec+1;
                                                        
                                                var nowy_element = '<div class="column" draggable="true" >    <div class="drop_zone" style="background:#e8e8e8; margin: 3px; border: 2px dashed #BBB;-moz-border-radius: 5px;-webkit-border-radius: 5px;border-radius: 5px;padding: 25px;text-align: center;font: 20pt bold \'Vollkorn\';color: #BBB;">'
                                                    +'<div class="item" style="min-height:140px;"></div>'
                                                    +'</div>'
                                                    +'<button onclick="deletePhoto(this);">Usun zdjecie</button>'
                                                    +'<button onclick="abortRead();">Przerwij wczytywanie</button>'                                                
                                                    +'<div class="progress_bar"><div class="percent">0%</div></div>    '
                                                    +'<input type="hidden" name="zdjecie[stara_nazwa]" value=""/>'
                                                    +'<input type="hidden" name="zdjecie[nowa_nazwa]" />    '
                                                    +'<input type="hidden" name="zdjecie[typ]" value="reg" />    '
                                                    +'<input type="hidden" name="zdjecie[logo]" value="0" />    '
                                                    +'</div><input type="hidden" name="zdjecie[pozycja]" value="' + (ilosc_zdjec+1) + '" />    ';
                                                            
                                                
                                                jQuery(ajax_object_docelowy).parents('table:first').find('[name="zdjecie[pozycja]"]').each(function(){
                                                    if(jQuery(this).val() == ilosc_zdjec) {
                                                        var w_kolumnie = 3;  
                                                        
                                                        if(typeof(ilosc_zdjec_w_kolumnie) != 'undefined')
                                                        if(ilosc_zdjec_w_kolumnie == 2)
                                                            w_kolumnie = 2;
                                                            
                                                        if(ilosc_zdjec % w_kolumnie == 0) 
                                                            jQuery(this).parents('tr:first').after('<tr><td>'+nowy_element+'</td></tr>');
                                                        else
                                                            jQuery(this).parents('td:first').after('<td>'+nowy_element+'</td>');
                                                    }
                                                });
                                                //if(ilosc_zdjec % 3 == 0) 
                                                //    jQuery(ajax_object_docelowy).parents('tr:first').after('<tr><td>'+nowy_element+'</td></tr>');
                                                //else
                                                //    jQuery(ajax_object_docelowy).parents('td:first').after('<td>'+nowy_element+'</td>');
                                            }
                                            dodajEventy();
                                        }    
                                        else
                                        {
                                            //zapiszDaneWizytowkowe(ajax_object_docelowy);
                                        }
                                    }

                                };
                      })(files[0]);

                    // Read in the image file as a binary string.
                    reader.readAsBinaryString(files[0]);
                        
                    // Read in the image file as a data URL.
                    reader.readAsDataURL(files[0]);
                  }
                  
function handleDropImage(evt) {
    //alert('ok');    
    jQuery('img').each(function(){
      if(jQuery(this).attr('src') != undefined)
        if(jQuery(this).attr('src').indexOf('http://') != -1) {
            var str_bez_http = jQuery(this).attr('src').substr(jQuery(this).attr('src').indexOf('http://')+7);
            var str_reszta = str_bez_http.substr(str_bez_http.indexOf('/')+1);
            //alert(str_bez_http.substring(0, str_bez_http.indexOf('/'))); //domena
            var link = 'http://' + window.location.hostname + '/' + str_reszta;
            jQuery(this).attr('src', link);
        }
    });    
}                  
                
jQuery(document).ready(function(){
                         zmienna = jQuery('#progress_bar').find('.percent:first');//document.querySelector('.percent');
                         progress = zmienna[0];  
                         
                         
                         jQuery('img').each(function(){
                            
                            var obj = jQuery(this);
                            obj = obj[0];
                            
                           if(jQuery(this).attr('src') != undefined)
                            if(jQuery(this).attr('src').indexOf('http://') != -1) {
                                    var str_bez_http = jQuery(this).attr('src').substr(jQuery(this).attr('src').indexOf('http://')+7);
                                    var str_reszta = str_bez_http.substr(str_bez_http.indexOf('/')+1);
                                    //alert(str_bez_http.substring(0, str_bez_http.indexOf('/'))); //domena
                                    var link = 'http://' + window.location.hostname + '/' + str_reszta;
                                    jQuery(this).attr('src', link);                               
                            }
                                                    
                         });
                         
                         /*
                         var images = document.querySelectorAll('#edit_textarea_omnie img');
                        [].forEach.call(images, function(image) {
                              image.setAttribute('draggable', 'true');  // Enable columns to be draggable.              
                              image.addEventListener('dragstart', handleDragStart, false);
                              image.addEventListener('dragenter', handleDragEnter, false)
                              image.addEventListener('dragover', handleDragOver, false);
                              image.addEventListener('dragleave', handleDragLeave, false);
                              image.addEventListener('drop', handleDrop, false);
                              image.addEventListener('dragend', handleDropImage, false);
                        });
                           */
                                                     
                    });
