var fileListBackground;
var premiumlightbox;
var countdown = 10;
var currentFile = 0;
var filesCount = 0;
var loaded = false;
var nothingChecked = false;
var fileListBackground;
var dialog;
var as_json;

function loadSubSpecifics() {
    
    Q(".ui-widget-overlay").click(function() {
        edisk.hideDialog();
    });
    
    if (check_adult && do_adult_check) {
        var res = false;
        if (xxx)
            res = confirm(lang.transl('NUDE_CONFIRM_LONG_XXX'));
        else
            res = confirm(lang.transl('NUDE_CONFIRM_LONG'));

        if (!res) {
            show_images = false;
            edisk.loadAjax('x-unset-adult-check', false, function() {
                if (xxx)
                    window.location.href = 'http://www.'+ed_dns_basename;
                else
                    window.location.href = '/';
            });
        }
        else {
            edisk.loadAjax('x-set-adult-check', '', function() {
                Q(".slideshow").each(function() {
                    Q(this).children("img:first").show();
                });
                Q("#file-preview").removeClass('x');
                return true;
            });
        }
    } else {
        Q(".slideshow").each(function() {
            Q(this).children("img:first").show();
        });
        Q("#file-preview").removeClass('x');
    }
    
    Q('#tab_search .bigbutton').click(function(){Q("#searchTerm").focus();});
    if (location.pathname == '/flash-user' && swfu == null)
        loadMultiUploadFlash();
    Q('#main_tabs_search').click(function() {
        Q('#tab_upload').hide();
        Q('#tab_search').show();
        Q('#main_tabs_upload').removeClass('active');
        Q(this).addClass('active');
    });
    Q('#main_tabs_upload').click(function() {
        Q('#tab_upload').show();
        Q('#tab_search').hide();
        Q('#main_tabs_search').removeClass('active');
        Q(this).addClass('active');
    });
    
    if (!isie) {
        Q('.show_block').click(function() {Q(".toggleBlocks").not('#'+Q(this).attr('id')+'_block').hide();Q('#'+Q(this).attr('id')+'_block').toggle();});
        Q('#lang_block_container').mouseenter(function() {
            Q(this).css('height', '150px');
            Q(".toggleBlocks").not('#'+Q(this).attr('id')+'_block').hide(); 
            Q('#show_langs_block').show();
            
        });
        Q("#login_block_container").mouseenter(function() {
            Q(this).css('height', '150px');
        });
        Q('.loginbutton').mouseenter(function() {
            Q(".toggleBlocks").not('#'+Q(this).attr('id')+'_block').hide();
            Q('#show_login_block').show(); 
        });
        Q('#login_block_container').mouseleave(function() {
            Q('#show_login_block').hide();
            Q(this).css('height', '30px');
        });
        Q('#lang_block_container').mouseleave(function() {
            Q('#show_langs_block').hide();
            Q(this).css('height', '30px');
        });
    } else {
        Q('.show_block').click(function() {Q(".toggleBlocks").not('#'+Q(this).attr('id')+'_block').hide();Q('#'+Q(this).attr('id')+'_block').toggle();});
    }
    //Q('#show_langs').click(function() {Q(".toggleBlocks").not('#lang_block').hide(); Q('#lang_block').toggle();});
    Q('.selectit').click(function() {Q(this).select();});
    Q('.getLinks').click(function () {getLinks(Q(this).attr('href'));return false;});
    Q('.moveFiles').click(function () {moveFiles(Q(this).attr('href'));return false;});
    Q('.editFiles').click(function () {editFiles(Q(this).attr('href'));return false;});
    Q('.sendFiles').click(function () {sendFiles(Q(this).attr('href'));return false;});
    Q('.newFolder').click(function () {newFolder(Q(this).attr('href'));return false;});
    
    Q('.folderRow').each(function() {
        Q(this).bind(
            "mouseover",
            function(){
                var folderid = Q(this).attr('id').substr(6);
                Q('#iconnormal_'+folderid).hide();
                Q('#iconopen_'+folderid).show();
            }
        );
        Q(this).bind(
            "mouseout",
            function(){
                var folderid = Q(this).attr('id').substr(6);
                Q('#iconopen_'+folderid).hide();
                Q('#iconnormal_'+folderid).show();
            }
        );
    });

    Q('#fileList tr').mouseover(function() {
        fileListBackground = Q(this).css('background-color');
        Q(this).css('background-color', '#f2f2f2');
    });
    Q('#fileList tr').mouseout(function() {
        Q(this).css('background-color', fileListBackground);
    });
    var searchBlock = Q(".cssdropdown.fr li.headlink ul.vyhledavani");
    if (searchBlock.hasClass("homepage")) {
        Q(searchBlock).show();
        var sipecka = Q(searchBlock).parent("li").children('.sipeckaspan');
        sipecka.css('background-position', '-64px 0');
    }
    if (Q('#siteMsg').html() != '') {
        edisk.showMessage(Q('#siteMsg').html());
    }
    
    Q('.showFileInfoButton').click(function() {
        var id = Q(this).attr('id').substr(6);
        Q('#toggleinfo'+id).toggle();
        Q('#showFileInfoButtonSubmit').show();
    });

    Q(".toggletab").click(function() {
        /*Q(".slideshow img").show();*/
        Q(".toggletab").removeClass('active');
        Q(this).addClass('active');
        var id = Q(this).attr('id');
        Q(".tab").addClass('x');
        Q("#"+id+"-div").removeClass('x');
        if (Q("#"+id+"-div-audio").length > 0) {
            Q("#"+id+"-div-audio").removeClass('x');
        }
    });
    
    Q(".cssdropdown li.headlink a").click(function() {
        var sipecka = Q(this).parent("li").children('.sipeckaspan');
        Q(".sipeckaspan").not(sipecka).css('background-position', '0px 0');
        Q(".cssdropdown ul").not(Q(this).parent("li").children("ul")).hide();
        Q(this).parent("li").children("ul").toggle();

       
        if(Q(this).parent("li").children("ul").is(':hidden'))
            sipecka.css('background-position', '0px 0');
        else
            sipecka.css('background-position', '-64px 0');
    });

    if (premiumlightbox) {
        var url = '';
        var params = 'slots=1';
        if (profi) url = 'x-premium-profi/';
        else url = 'x-premium/';
        edisk.loadAjax(url+premiumlightboxid, params, function(req) {
            edisk.hideDialog();
            showDialog(req); 
        });
    }

    Q("#search_expand").click(function() {
       Q("#search_expand_cats").toggle();
    });

    Q(".search_cat_check").click(function() {
       if (Q(this).is(":checked")) {
           var checkid = Q(this).attr('id');
           Q(".search_cat_check").attr('checked', false);
           Q(this).attr('checked', true);
           if (checkid != 'search_account')
              Q('#header #searchForm').submit();
       }
    });

    Q('.change_cat').click(function() {
        var id = Q(this).attr('id');
        Q("tr.letters").hide();
        Q("tr.letters_catname").hide();
        Q("#letters_"+id).show();
        Q("#letters2_"+id).show();
        Q("#letters_catname_"+id).show();
    });
    
    loadColorbox();
    loadToolTip('');
    loadSlider();
    lateLoad();
    loadFacebook();

    
    
    return true;
}


function hideMsg() {
    document.getElementById('siteMsg').style.visibility = 'hidden';
}

function submitSearchForm() {
    var catid = 0;
    Q(".search_cat_check").each(function() {
       if (Q(this).is(":checked")) {
           catid = Q(this).attr('id').substr(11);
       }
    });
    var searchaction = Q("searchForm").attr('action');
    if (Q('#search_account').is(":checked")) {
        Q('#searchForm').attr('action', Q('#hiddenaction').val());
    } else {
        Q('#searchForm').attr('action', searchaction);
    }
    if (Q("#searchTerm").val() == '') alert(lang.transl("SEARCH_FIELD_DEFAULT"));
    else if (Q("#searchTerm").val() == lang.transl("SEARCH_FIELD")) alert(lang.transl("SEARCH_FIELD_DEFAULT"));
    else if (check_adult && catid == adult_catid) {
      if (!confirm(lang.transl("NUDE_CONFIRM"))) return false;
      document.forms.searchForm.submit();
    }
    else document.forms.searchForm.submit();
    return true;
}

function checkNudeCat() {
    if (check_adult && !confirm(lang.transl('NUDE_CONFIRM'))) return false;
    else return true;
}

function loadFacebook() {
    if (Q("#facebookframe").length > 0)
        Q("#facebookframefooter").hide();
    if (Q('#facebookframe').length > 0)
        Q('#facebookframe').html('<iframe src="http://www.facebook.com/plugins/like.php?href=http%3A%2F%2Fwww.facebook.com%2Fpages%2FeDisk%2F131317500235107&amp;layout=button_count&amp;show_faces=false&amp;width=450&amp;action=like&amp;colorscheme=light&amp;height=21" scrolling="no" frameborder="0" style="border:none; overflow:hidden; width:450px; height:21px;" ></iframe>');
    if (Q('#facebookframefooter').length > 0)
        Q('#facebookframefooter').html('<iframe src="http://www.facebook.com/plugins/like.php?href=http%3A%2F%2Fwww.facebook.com%2Fpages%2FeDisk%2F131317500235107&amp;layout=button_count&amp;show_faces=false&amp;width=450&amp;action=like&amp;colorscheme=light&amp;height=21" scrolling="no" frameborder="0" style="border:none; overflow:hidden; width:450px; height:21px;"></iframe>');
    if (Q('#fblike').length > 0)
        Q('#fblike').html('<span><iframe src="http://www.facebook.com/plugins/like.php?href='+location.href+'&amp;layout=button_count&amp;show_faces=false&amp;action=like" scrolling="no" frameborder="0" style="border:none; overflow:hidden; width:140px; height: 25px;" allowTransparency="true"></iframe></span>');
}

function loadSlider() {
    var container = Q('div.sliderGallery');
    var ul = Q('ul', container);

    var itemsWidth = ul.innerWidth() - container.outerWidth();

    Q('.slider', container).slider({
        min: 0,
        max: itemsWidth,
        handle: '.handle',
        stop: function (event, ui) {
            ul.animate({'left' : ui.value * -1}, 500);
        },
        slide: function (event, ui) {
            ul.css('left', ui.value * -1);
        }
    });
}

function showDialog(msg, buttons) {
    edisk.showDialog(msg, buttons);
    reload();
}

function lateLoad() {

    Q('.lateloadhide').each(function() {
       Q(this).css('visibility', 'hidden');
    });
    Q('.lateload').each(function() {
       Q(this).css('visibility', 'visible');
    });
    
    Q('.star-rating a').click(function() {
       var form = Q(this).parents('form:first');
       submit_star_rating(parseInt(Q(this).attr('title')), Q('#star_rating_fileid').val());
       return false;
    });
    
}

function showCommentTab() {
    Q(".toggletab").removeClass('active');
    Q('#tab-komentare').addClass('active');
    Q(".tab").addClass('x');
    Q('#tab-komentare-div').removeClass('x');
}

function reload() {
    Q('.reload_lightbox').click(function(ev) {
        ev.preventDefault();
        var url = Q(this).attr('href');
        
        edisk.dialog.dialog("close");
        edisk.loadAjax(url, '', function(req) {
            showDialog(req);
            return true;
        });
    });
}

function submit_star_rating(value, fileid) {
    var url = 'x-submit-star-rating';
    var params = 'rating='+value+'&fileid='+fileid;
    edisk.loadAjax(url, params, function(msg) {
        if (msg == 1) {
          Q('#rating2').rating('select', value-1);
          Q('#rating2').rating('disable');
          Q('#canVote').hide();
          alert(lang.transl('VOTED'));
        }
        showCommentTab();
        return true;
    });
    return false;
}

function submitPaypal(id) {
    var params = 'id='+id;
    if (Q("#paypal_new_email").length > 0) {
        params += '&paypal_new_email='+Q("#paypal_new_email").val();
    }
    
    var url = 'x-generate-paypal-hash';
    edisk.loadAjax(url, params, function(msg) {
        if (msg != 'error' && msg.substr(0, 6) != 'error_' && msg.length > 32 && msg.length <= 50) {
            
          Q('#paypal'+id+" #custom").attr('value', msg);
          Q('#paypal'+id).submit();
        }
        else if (msg.substr(0, 6) == 'error_') {
            alert(msg.substr(6));
            return false;
        } else {
            alert(lang.transl("ERROR_PAYPAL"));
            return false;
        }
        return false;
    });
    return false;
}

function checkPaypalComplete() {
    var params = '';
    var url = 'x-check-paypal-hash';
    edisk.loadAjax(url, params, function(msg) {
        if (msg == 'OK') {
          Q(".hideoncomplete").hide();
          Q(".showoncomplete").show();
          wait();
        }
        else {
          Q(".hideoncomplete").hide();
          Q(".showonerror").show();
          Q(".error_p").hide();
        }
        return false;
    });
    return false;
}

function setCountryPaymentsQuick(member) {
    var selected = Q("#country");
    var country = selected.val();
    var file_id = Q('input[name=file_id]').val();
    showPayment(file_id, country, member);
    return false;
}

function setCountryPaymentsPromoCredit() {
    var selected = Q("#country");
    var country = selected.val();
    window.location = edisk.getBasename() + '/setcredit/' + country;
    return true;
}

function setCountryPaymentsPromo() {
    var selected = Q("#country");
    var country = selected.val();
    window.location = edisk.getBasename() + '/promo/' + country;
    return true;
}

function setCountryPaymentsPromoAccount(link) {
    var selected = Q("#country");
    var country = selected.val();
    window.location = link + '/' + country;
    return true;
}

function setCountryPayments() {
    var selected = Q("#country");
    var url = selected.val();
    var params = '';
    edisk.dialog.dialog('close');
    edisk.loadAjax(url, params, function(msg) {
        showDialog(msg, false);
    });
    return false;
}

function setCountryCreditPayments(id) {
    var selected = Q("#country");
    var url = 'x-credit-sms'+'/'+id+'/'+selected.val();
    var params = '';
    edisk.dialog.dialog('close');
    edisk.loadAjax(url, params, function(msg) {
        showDialog(msg, false);
    });
    return false;
}

function sendFormSubmit(formName, template) {
    var valid = true;
    var url = 'x-'+formName;
    var params = 'template='+template;
    Q("#"+formName+" .required").each(function() {
        var id = Q(this).attr('id');
        if (Q(this).attr('value') == '') {
            alert(lang.transl("EMPTY_FIELD") + " " + Q('#'+ id + "_label").html());
            valid = false;
        }
    });
    Q("#"+formName+" input").each(function() {
        params += '&'+Q(this).attr('name')+'='+encodeURIComponent(Q(this).attr('value'));
    });
    if (!valid) return false;
    edisk.loadAjax(url, params, function(msg) {
        edisk.showMessage(msg);
        edisk.dialog.dialog("close");
    });
    return true;
}

function countDown(action, waitSecs){

    var line = Q('#countDownLine');
    line = lang.transl("DOWNLOAD_WAIT_PART1") + '<span class="orange">' + waitSecs + "s.</span>";

    if (waitSecs > 0){
        waitSecs--;
        Q('#countDown').html(line);
        dlTimeOut = setTimeout('countDown(\''+action+'\', \''+waitSecs+'\');', 1000);
    } else {
        var params = 'action='+action;
        var url = 'x-download/' + action;
        edisk.loadAjax(url, params, function(msg) {
            setDownloadText(msg);
        });
    }
}
function countDownMember(action, waitSecs){
    
    var line = Q('#countDownLine');
    line = lang.transl("DOWNLOAD_WAIT_PART1") + '<span class="orange">' + waitSecs + "s.</span>";
    
    if (waitSecs > 0) {
        waitSecs--;
        Q('#countDown').html(line);
        dlTimeOut = setTimeout('countDownMember(\''+action+'\', \''+waitSecs+'\');', 1000);
    } else {
        var params = 'action='+action;
        var url = 'x-download-it/' + action;
        edisk.loadAjax(url, params, function(msg) {
            setDownloadText(msg);
        });
    }
}

function showCompanyTable(display){
    document.getElementById('comTableWrapper').style.display = display;
}

function showIndividualTable(display){
    document.getElementById('indTableWrapper').style.display = display;
}

function showEmailValidity(valid){
    if ( valid == 1){
        validEmail = true;
        Q('#invalidEmail').css('display', 'none');
        Q('#validEmail').css('display', 'block');
    } else {
        validEmail = false;
        Q('#validEmail').css('display', 'none');
        Q('#invalidEmail').css('display', 'block');
    }
}

function checkCommentForm() {
    var name = Q('#text').attr('value');
    var name2 = Q("input[@name='radio_name']:checked").val();
    
    if ( name.length <= 0 && !name2) {
        alert(lang.transl("NO_COMMENT_OR_RATING"));
        return false;
    } 
    return true;
}

function checkMail(addr){
    var url = 'x-check-email';
    if (addr.substr(0, 4) == 'www.') {addr = addr.replace('www.', '');} // people are stupid, type in emails with www
    var params = 'emailAddr='+encodeURIComponent(addr);
    Q('#regEmail').attr('value', addr);
    edisk.loadAjax(url, params, function(msg) {
        var l = parseInt(msg);
        if (l == 0)
          showEmailValidity(0);
        else {
          url = 'x-email-exists';
          edisk.loadAjax(url, params, function(msg_int) {
            if (parseInt(msg_int) == 0)
               showEmailValidity(1);
            else
               showEmailValidity(0);
          });  
        }
    });     
}

function showTip(name){
    Q('#'+name+'Hint').css('display', 'block')
}

function hideTip(name){
    Q('#'+name+'Hint').css('display', 'none');
}

function submitNewFolder() {
    var name = Q('#folderName').attr('value');
    var url = 'x-add-folder';
    
    if ( name.length <= 0 ){
        alert(lang.transl("NO_FOLDER_NAME"));
        return false;
    }
    
    var params = 'folder='+encodeURIComponent(name);
    edisk.loadAjax(url, params, function(msg) {
        if (msg != '') edisk.showMessage(msg);
        edisk.reloadPage();
    });
    return true;
}

//////
function checkForgottenMail(addr){
    var url = 'x-check-email';
    if (addr.substr(0, 4) == 'www.') {addr = addr.replace('www.', '');} // people are stupid, type in emails with www
    var params = 'emailAddr='+encodeURIComponent(addr);
    Q('#regEmail').attr('value', addr);
    edisk.loadAjax(url, params, function(msg) {
        var l = parseInt(msg);
        if (l == 0)
          showEmailValidity(l);
        else {
          url2 = 'x-email-exists';
          edisk.loadAjax(url, params, function(msg2) {
            if (parseInt(msg2) == 0)
                showEmailValidity(0);
            else
                showEmailValidity(1);
          });
        }
    });
}


function checkPassLen(){
    if (document.getElementById('regPass1').value.length < 5 ){
        alert(lang.transl("SHORT_PASS"));
        document.getElementById('regPass1').select();
        return false;
    } else {
        return true;
    }
}

function checkPassMatch(){
    if (document.getElementById('regPass1').value == '' ){
        alert(lang.transl("NO_PASS"));
        document.getElementById('regPass1').select();
        return false;
    }

    if (document.getElementById('regPass1').value != document.getElementById('regPass2').value ){
        alert(lang.transl("PASS_NOT_MATCH"));
        document.getElementById('regPass1').select();
        return false;
    } else {
        return true;
    }
}

function checkForm() {
    if ( document.getElementById('regEmail').value == '' ){
        alert(lang.transl("NO_EMAIL"));
        return false;
    }

    if ( !checkPassLen() ){
        return false;
    }

    if ( !checkPassMatch() ){
        return false;
    }

    if ( !validEmail ){
        alert(lang.transl("EMAIL_NOT_VALID"));
        return false;
    }

    if ( document.getElementById('regCaptchaCode').value == '' ){
        alert(lang.transl("NO_CAPTCHA"));
        return false;
    }

    if ( !document.getElementById('termsAgreed').checked ){
        alert(lang.transl("NO_TERMS_AGREED"));
        return false;
    }

    document.getElementById('signupForm').submit();
    return true;
}

function showPaymentOptions(id) {
    for (var i=0; i<=3; i++)
      jQuery("#paymentTable"+i).hide();
    jQuery("#paymentTable"+id).show("slow");
}

function showPayOp(id) {
    document.getElementById("paymentTable"+id).width = "585px";
}

function checkAllIncFolders(){
    var check;

    if ( document.getElementById('fCheckCtrl').checked ){
        check = true;
    } else {
        check = false;
    }

    var cbA = document.getElementsByName('fileCheck[]');
    var cbF = document.getElementsByName('folderCheck[]');
    var i;
    for (i = 0; i < cbA.length; i++){
        cbA[i].checked = check;
    }

    for (i = 0; i < cbF.length; i++){
        cbF[i].checked = check;
    }
}

function checkAll(){

    var check = false;
    if ( document.getElementById('fCheckCtrl').checked){
        check = true;
    } else {
        check = false;
    }

    var cbA = document.getElementsByName('fileCheck[]');
    for (var i = 0; i < cbA.length; i++){
        cbA[i].checked = check;
    }

}

function filesAndFoldersParams() {
    var cbArray = getChecked('fileCheck[]');
    var cfArray = getChecked('folderCheck[]');

    if ( cbArray.length + cfArray.length <= 0 ){
        alert(lang.transl("NO_FILES"));
        return false;
    }

    var params = '';
    for(i = 0; i < cbArray.length; i++ ){
        params += '&fileCheck[]=' + cbArray[i];
    }
    for(i = 0; i < cfArray.length; i++ ){
        params += '&folderCheck[]=' + cfArray[i];
    }
    return params;
}

function getLinks(url){
    var params = filesAndFoldersParams();
    if (!params) return false;
    
    edisk.loadAjax(url, params, function(msg) {
        showDialog(msg, false);
    });
    return false;
}

function sendFilesSubmit() {
    var cbArray = getChecked('fileCheck[]');
    if ( cbArray.length <= 0 ){
        alert(lang.transl("NO_FILES"));
        return false;
    }
    
    var ids = cbArray.join('/');
    sendFileLink(ids);
    return true;
}

function newFolder(url) {
    
    var params = '';
    edisk.loadAjax(url, params, function(msg) {
        showDialog(msg, true);
        var createLabel = lang.transl("LABEL_CREATE");
        var buttons = {};
        buttons[ createLabel ] = function() {
            Q('#loadingDiv').show();
            if (submitNewFolder()) Q(this).dialog('close');
            else Q('#loadingDiv').hide();
        };
        edisk.dialog.dialog( "option", "buttons", buttons);
    });
    return false;
}

function sendFiles(url) {
    var cbArray = getChecked('fileCheck[]');
    if ( cbArray.length <= 0 ){
        alert(lang.transl("NO_FILES"));
        return false;
    }
    
    
    var params = '';
    edisk.loadAjax(url, params, function(msg) {
        showDialog(msg, false);
    });
    return false;
}

function editFiles(url) {
    var params = filesAndFoldersParams();
    if (!params) return false;
    edisk.loadAjax(url, params, function(msg) {
        showDialog(msg, true);
        var createLabel = lang.transl("LABEL_SAVE");
        var buttons = {};
        buttons[ createLabel ] = function() {
            Q('#loadingDiv').show();
            renameFilesSubmit();
            Q(this).dialog('close');
        };
        edisk.dialog.dialog( "option", "buttons", buttons);
        Q('.showFileInfoButton').click(function() {
            var id = Q(this).attr('id').substr(6);
            Q('#toggleinfo'+id).toggle();
        });
    });
    return false;
}

function buttonRename() {

}

function showPayment(file_id, paylang, member) {
    
    var url = '';
    var params = 'slots='+slots;
    
    if (member)
        url = 'x-options-sms-member/'+file_id+'/'+paylang;
    else
        url = 'x-options-sms-quick/'+file_id+'/'+paylang;
    
    edisk.loadAjax(url, params, function(msg) {
        showDialog(msg, false);
        edisk.dialog.bind( "dialogclose", function(event, ui) {
             Q('.download-button-orange').css('background', '#FF4100');
             Q('.download-button-orange').css('color', 'white');
        });
        Q('.download-button-orange').css('background', '#C5CACE');
        Q('.download-button-orange').css('color', '#333333');
    });
    return false;
}

function renameFilesSubmit() {
    var params = '';
    var files = new Array();
    var filesnames = new Array();
    var folders = new Array();
    var foldersnames = new Array();
    var filecats = new Array();
    var description = new Array();
    var privatefile = new Array();
    var items = null;

    items = document.getElementsByName('file_id[]');
    for(var i = 0; i < items.length; i++){
        files[files.length] = items[i].value;
    }
    items = document.getElementsByName('file_name[]');
    for(var j = 0; j < items.length; j++){
        filesnames[filesnames.length] = items[j].value;
    }
    items = document.getElementsByName('description[]');
    for(var m = 0; m < items.length; m++){
        description[description.length] = items[m].value;
    }
    items = document.getElementsByName('filecats[]');
    for(var n = 0; n < items.length; n++){
        filecats[filecats.length] = items[n].value;
    }
    items = document.getElementsByName('private[]');
    for(var o = 0; o < items.length; o++){
        privatefile[privatefile.length] = items[o].checked;
    }
    items = document.getElementsByName('folder_id[]');
    for(var k = 0; k < items.length; k++){
        folders[folders.length] = items[k].value;
    }
    items = document.getElementsByName('folder_name[]');
    for(var l = 0; l < items.length; l++){
        foldersnames[foldersnames.length] = items[l].value;
    }

    for(i = 0; i < files.length; i++ ){
        params += '&file[]=' + files[i];
    }
    for(i = 0; i < filesnames.length; i++ ){
        params += '&filename[]=' + filesnames[i];
    }
    for(i = 0; i < folders.length; i++ ){
        params += '&folder[]=' + folders[i];
    }
    for(i = 0; i < foldersnames.length; i++ ){
        params += '&foldername[]=' + foldersnames[i];
    }
    for(i = 0; i < filecats.length; i++ ){
        params += '&filecats[]=' + filecats[i];
    }
    for(i = 0; i < description.length; i++ ){
        params += '&description[]=' + description[i];
    }
    for(i = 0; i < privatefile.length; i++ ){
        params += '&privatefile[]=' + privatefile[i];
    }
    
    var url = 'x-rename-files-submit';
    edisk.loadAjax(url, params, function(msg) {
        edisk.reloadPage();
    });
    return true;
}

function moveFiles(url) {
    var cbArray = getChecked('fileCheck[]');
    if ( cbArray.length <= 0 ){
        alert(lang.transl("NO_FILES"));
        return false;
    }

    var params = '';
    for(i = 0; i < cbArray.length; i++ ){
        params += '&fileCheck[]=' + cbArray[i];
    }
    
    edisk.loadAjax(url, params, function(msg) {
        showDialog(msg, true);
        var createLabel = lang.transl("LABEL_MOVE");
        var buttons = {};
        buttons[ createLabel ] = function() {
            Q('#loadingDiv').show();
            moveFilesSubmit(false);
            Q(this).dialog('close');
        };
        edisk.dialog.dialog( "option", "buttons", buttons);
    });
    return true;
}

function moveFilesSubmit(all_same) {
    var params = '';
    var files = new Array();
    var folders = new Array();
    items = document.getElementsByName('file_id[]');
    for(var i = 0; i < items.length; i++){
        files[files.length] = items[i].value;
    }
    items = document.getElementsByName('folder_id[]');
    
    var all_value = document.getElementsByName('folder_id_all')[0].value;
    
    for(var j = 0; j < items.length; j++){
        if (all_value >= 0 && all_same)
            folders[folders.length] = all_value;
        else
            folders[folders.length] = items[j].value;
    }

    for(i = 0; i < files.length; i++ ){
        params += '&file[]=' + files[i];
    }
    for(i = 0; i < folders.length; i++ ){
        params += '&folder[]=' + folders[i];
    }

    var url = 'x-move-files-submit';
    edisk.loadAjax(url, params, function(msg) {
        moveFilesSubmit(true);
        if (all_same)
            edisk.reloadPage();
    });
    return true;
}

function checkSearchForm(searchlink) {
    
    if (Q('#searchTerm2').attr('value') == lang.transl('SEARCH_FIELD')) Q('#searchTerm2').attr('value', '');

    if (Q('#allfiles').attr('checked')) {
        Q('#searchForm2').attr('action', searchlink);
        Q('#searchForm2').submit();
    }
    else {
        Q('#searchForm2').submit();
    }
    
}

function deleteFiles(){
    var cbArray = getChecked('fileCheck[]');
    if ( cbArray.length <= 0 ){
        alert(lang.transl("NO_FILES"));
        return false;
    }

    if ( confirm(lang.transl("CONFIRM_MULTI_DELETE"))){
        var params = '';
        for(i = 0; i < cbArray.length; i++ ){
            params += '&fileCheck[]=' + cbArray[i];
        }
        var url = 'x-unlink-files';
        edisk.loadAjax(url, params, function(msg) {
            edisk.reloadPage();
        });
        return true;
    }
    else return false;
}

function deleteFilesAndFolders(url){

    var cbArray = getChecked('fileCheck[]');
    var foldArray = getChecked('folderCheck[]');

    if ( cbArray.length <= 0 && foldArray <= 0){
        alert(lang.transl("NO_FILES_OR_FOLDERS"));
        return false;
    }

    var params = '';
    for(i = 0; i < cbArray.length; i++ ){
        params += '&fileCheck[]=' + cbArray[i];
    }
    
    if ( confirm(lang.transl("CONFIRM_MULTI_DELETE_BOTH"))){
        edisk.loadAjax(url, params, function(msg) {
            deleteFolders(msg);
            //edisk.reloadPage();
        });
        return true;
    }
    else {
        return false;
    }
}

function deleteFolders(msgOuter) {
    var params = '';
    var foldArray = getChecked('folderCheck[]');
    for(i = 0; i < foldArray.length; i++ ){
        params += '&folderCheck[]=' + foldArray[i];
    }
    var url = 'x-unlink-folders';
    edisk.loadAjax(url, params, function(msg) {
        edisk.showMessage(msg + ' ' + msgOuter);
        edisk.reloadPage();
    });
    return true;
}

function check_code_sms() {
    
    var code = Q("#code").attr('value');
    var file_id = Q("#file_id").attr('value');
    if (Q('#code').attr('value') == '') {
        alert(lang.transl("NO_CODE"));
        return false;
    }
    var params = 'code='+code;
    if (file_id) params += '&file_id='+file_id;
    
    var url = 'x-is-valid-sms-code';
    edisk.loadAjax(url, params, function(msg) {
        if (msg.substr(0, 6) == 'error_') {
            alert(msg.substr(6));
        } else {
            Q('.warning_lightbox').hide();
            Q('#quickDownloadTable').hide();
            Q('#creditStep').hide();
            Q('.lightboxnotsowideline').hide();
            
            Q("#dl_sms_payment").hide();
            Q("#dl_login_block").hide();
            Q("#dl_slow_block").hide();
            if (Q('#creditStepHidden').length > 0) {
                Q('#creditStepHidden').show();
                edisk.dialog.dialog("option", "width", 400);
                edisk.dialog.dialog("option", "height", 170);
                edisk.dialog.dialog("option", "position", 'center');
            } else {
                edisk.dialog.dialog("destroy");
            }
            Q('#submitCode').submit();
        }
    });
    return false;
}

function downloadPremium() {
    Q('#dialog .showit').hide();
    Q('#dialog .hideit').show();
}

function voteWall(id, state) {
    var params = 'id='+id+'&state='+state;
    var url = 'x-vote-wall';
    edisk.loadAjax(url, params, function(msg) {
        if (msg.substr(0, 6) == 'error_')
          alert(msg.substr(6));
        else {
            if (state == 1) {
                var count_yes = parseInt(Q('#rating_yes_'+id).html());
                Q('#rating_yes_'+id).html(count_yes+1);
            } else {
                var count_no = parseInt(Q('#rating_no_'+id).html());
                Q('#rating_no_'+id).html(count_no+1);
            }
            alert(lang.transl("VOTE_OK"));
        }
    });
    return false;
}

function check_code(){
    var code = Q("#code").attr('value');
    if (code == '') {
        alert(lang.transl("NO_CODE"));
        return FALSE;
    }

    var params = 'code='+code;
    var url = 'x-is-valid-sms-code';
    edisk.loadAjax(url, params, function(msg) {
        if (msg.substr(0, 6) == 'error_')
          alert(msg.substr(6));
        else {
          alert(lang.transl("VALUE_ADDED") + " " + msg.substr(3) + " " + 'MB');
          document.getElementById("paymenttype").innerHTML = 'SMS';
          document.getElementById("valuemb").innerHTML = msg.substr(3);
          document.getElementById("valueadded").style.display = 'block';
          document.getElementById("usercredit").innerHTML = parseInt(document.getElementById("usercredit").innerHTML) + parseInt(msg.substr(3));
          setTimeout("removeValueAdded()", 4000);
          Q("#dialog").dialog('close');
          edisk.reloadPage();
        }
    });
    return true;
}

function removeValueAdded() {
    document.getElementById("valueadded").style.display = 'none';
}

function getChecked(elName){
    var checked = new Array();
    cbA = document.getElementsByName(elName);
    for(var i = 0; i < cbA.length; i++){
        if (cbA[i].checked){
            checked[checked.length] = cbA[i].value;
        }
    }
    return checked;
}

function checkPassEqual(){
    var pass1 = document.getElementById('passwd1').value;
    var pass2 = document.getElementById('passwd2').value;
    if ( pass1 != pass2 ){
        alert(lang.transl("PASS_NOT_MATCH"));
        return false;
    } else {
        return true;
    }
}

function checkSettingsForm() {
    if ((document.getElementById('passwd1').value.length > 0) || (document.getElementById('passwd2').value.length > 0) || (document.getElementById('currentPasswd').value.length > 0))
    {
        if (!checkPassLen2()) return false;
        if (!checkPassEqual()) return false;
    }

    var ret = window.confirm(lang.transl("REALLY_SAVE"));
    if (!ret) {
        return false;
    }
    document.getElementById('userSettingsForm').submit();
    return true;
}

function checkPassLen2(){
    if ( document.getElementById('passwd1').value.length < 5 ){
        alert(lang.transl("SHORT_PASS"));
        document.getElementById('passwd1').select();
        return false;
    } else {
        return true;
    }
}

function checkElementEmpty(element, errMsg){
    if ( document.getElementById(element).value.length == 0 ){
        alert(errMsg);
        document.getElementById(element).select();
        return false;
    } else {
        return true;
    }
}

function deleteAcc() {
    var ret = window.confirm(lang.transl("CONFIRM_ACCOUNT_DROP"));
    if (!ret) {
        return false;
    }
    document.getElementById('userDeleteForm').submit();
    return true;
}

function sendFileLink(ids) {
    var email = encodeURIComponent(Q('#contactEmail').val());
    if (!email) {alert(lang.transl("NO_EMAIL"));return false;}
    var name = encodeURIComponent(Q('#contactName').val());
    if (!name) {alert(lang.transl("NO_NAME"));return false;}
    var params = '';
    params += '&fileId=' + ids;
    params += '&contactEmail=' + email;
    params += '&contactName=' + name;
    
    if (email != '') {
        var url = 'send-links';
        edisk.loadAjax(url, params, function(msg) {
            edisk.showMessage(msg);
            edisk.dialog.dialog("close");
        });
    }
    return true;
}

function goToFolder(id) {
    var params = 'folder='+id;
    var url = 'x-change-folder';
    edisk.loadAjax(url, params, function(msg) {
        edisk.reloadPage();
    });
}

function copy(text2copy) {
    if (window.clipboardData) {
        window.clipboardData.setData("Text",text2copy);
    }
    else {
        var flashcopier = 'flashcopier';
        if(!document.getElementById(flashcopier)) {
            var divholder = document.createElement('div');
            divholder.id = flashcopier;
            document.body.appendChild(divholder);
        }
        document.getElementById(flashcopier).innerHTML = '';
        var divinfo = '<embed src="http://www.edisk.cz/images/_clipboard.swf" FlashVars="clipboard='+escape(text2copy)+'" width="0" height="0" type="application/x-shockwave-flash"></embed>';
        document.getElementById(flashcopier).innerHTML = divinfo;
    }
}

function selectbeforecopy(element)
{
    document.getElementById(element).focus();
    document.getElementById(element).select();
    copy(document.getElementById(element).value);
}

function selectbeforecopyAll(count)
{
    var text = '';
    for (i = 1; i <= count; i++) {
        text += document.getElementById('plainLink_'+i).value;
        text += '\n';
        text += document.getElementById('deleteLink_'+i).value;
        text += '\n';
    }

    copy(text);
    alert(lang.transl("COPY_DONE"));
}

function changeFile(id) {
    if (filesCount >= 5) return false;

    var element = document.getElementById('selectedFile'+id);
    var fileName = document.getElementById('upfile_'+id).value;
    var fileInputBox = document.getElementById('fileInputBox'+id);
    var ext = fileName.substr(fileName.lastIndexOf('.') + 1, 4);
    ext = ext.toLowerCase();
    var extension = new Array("avi", "bz2", "c", "cpp", "doc", "exe", "gif", "gz", "html", "img", "jpeg", "jpg", "js", "mp3", "mpeg", "mpg", "msi", "nfo", "pdf", "php", "png", "ppt", "psd", "rar", "rtf", "swf", "txt", "wav", "wma", "wmv", "xls", "zip");
    if (extension.indexOf(ext) > 0) {}
    else {ext = 'unknown';}

    element.style.paddingLeft = '25px';
    element.style.background = 'url(../images/icons/' + ext + '.png) no-repeat 3px 2px';
    var filteredName = fileName.substr(fileName.lastIndexOf('/') + 1);
    filteredName = fileName.substr(fileName.lastIndexOf('\\') + 1);
    if (filteredName.length > 30)
    filteredName = filteredName.substr(0, 30) + ' ...';
    element.innerHTML = filteredName;


    document.getElementById('files').style.display = 'block';
    var para = document.createElement('p');
    para.innerHTML = filteredName + '<img src="/images/cross.gif" class="deleteFileIco" onclick="deleteFile('+currentFile+');"/>';
    para.className = 'filePara';
    para.id = 'para_' + currentFile;
    para.style.background = 'url(../images/icons/' + ext + '.png) no-repeat 3px 2px';
    document.getElementById('files').insertBefore(para, document.getElementById('para_' + currentFile));

    currentFile++;
    addSlot();
    filesCount++;
    return true;
}

function deleteFile(id) {
    var remove = document.getElementById('para_' + id);
    var remove2 = document.getElementById('con' + id);
    var old = document.getElementById('files');
    var old2 = document.getElementById('upload_slots');
    old.removeChild(remove);
    old2.removeChild(remove2);
    max_upload_slots++;
}

function changeAsc() {
    if (document.getElementById('hiddenAsc').value == 'ASC')
        document.getElementById('hiddenAsc').value = 'DESC';
    else
        document.getElementById('hiddenAsc').value = 'ASC';
}

function addSlot() {

    var element = document.createElement('div');
    element.id = 'con' + currentFile;
    element.className = 'con';

    var input = document.createElement('div');
    input.id = 'fileInputBox' + currentFile;

    var button = document.createElement('div');
    button.className = 'button btn2';

    var browse = document.createElement('a');
    browse.href = 'javascript:void(0);';
    browse.id = 'browseFile' + currentFile;
    var left = document.createElement('span');
    left.className = 'left';
    var center = document.createElement('span');
    center.className = 'center smaller';
    center.style.fontSize = '11px';
    center.innerHTML = 'Vybrat';
    var right = document.createElement('span');
    right.className = 'right';

    button.appendChild(browse);
    button.appendChild(left);
    button.appendChild(center);
    button.appendChild(right);

    var sel = document.createElement('div');
    sel.className = 'selectedFile';
    sel.id = 'selectedFile' + currentFile;
    sel.innerHTML = 'není vybrán soubor';

    var wrap = document.createElement('div');
    wrap.className = 'inputWrapper';


    wrap.innerHTML = '<input type="file" id="upfile_'+currentFile+'" name="upfile_'+currentFile+'" size="35" class="jsuFileInput" onchange="changeFile('+currentFile+');"/>';

    input.appendChild(button);
    input.appendChild(sel);
    input.appendChild(wrap);

    element.appendChild(input);
    var parent = document.getElementById('upload_slots');
    var before = document.getElementById('con' + (currentFile - 1));

    parent.insertBefore(element, before);
    document.getElementById('con' + (currentFile - 1)).style.display = 'none';
    //alert(document.getElementById('upload_slots').innerHTML);
}

function wait(){
    
    if (countdown > 0) {
        document.getElementById('countdownspan').innerHTML = '<b>' + countdown + '</b>';
        countdown -= 1;
        setTimeout('wait()', 1000);
    }
    else {
        document.getElementById('countdownspan').innerHTML = '<b>' + countdown + '</b>';
        setTimeout('edisk.setHomeLocation()', 0);
    }
}

function loadColorbox() {

    // ColorBox v1.3.6 - a full featured, light-weight, customizable lightbox based on jQuery 1.3
    // c) 2009 Jack Moore - www.colorpowered.com - jack@colorpowered.com
    // Licensed under the MIT license: http://www.opensource.org/licenses/mit-license.php

    (function ($) {
            // Shortcuts (to increase compression)
            var colorbox = 'colorbox',
            hover = 'hover',
            TRUE = true,
            FALSE = false,
            cboxPublic,
            isIE = $.browser.msie && !$.support.opacity, // feature detection alone gave false positives in some browsers
            isIE6 = isIE && $.browser.version < 7,

            // Event Strings (to increase compression)
            cbox_open = 'cbox_open',
            cbox_load = 'cbox_load',
            cbox_complete = 'cbox_complete',
            cbox_cleanup = 'cbox_cleanup',
            cbox_closed = 'cbox_closed',
            cbox_resize = 'resize.cbox_resize',

            // Cached jQuery Object Variables
            $overlay,
            $cbox,
            $wrap,
            $content,
            $topBorder,
            $leftBorder,
            $rightBorder,
            $bottomBorder,
            $related,
            $window,
            $loaded,
            $loadingBay,
            $loadingOverlay,
            $loadingGraphic,
            $title,
            $current,
            $slideshow,
            $next,
            $prev,
            $close,

            // Variables for cached values or use across multiple functions
            interfaceHeight,
            interfaceWidth,
            loadedHeight,
            loadedWidth,
            element,
            bookmark,
            index,
            settings,
            open,
            active,

            // ColorBox Default Settings.
            // See http://colorpowered.com/colorbox for details.
            defaults = {
                    transition: "elastic",
                    speed: 350,
                    width: FALSE,
                    height: FALSE,
                    innerWidth: FALSE,
                    innerHeight: FALSE,
                    initialWidth: "400",
                    initialHeight: "400",
                    maxWidth: FALSE,
                    maxHeight: FALSE,
                    scalePhotos: TRUE,
                    scrolling: TRUE,
                    inline: FALSE,
                    html: FALSE,
                    iframe: FALSE,
                    photo: FALSE,
                    href: FALSE,
                    title: FALSE,
                    rel: FALSE,
                    opacity: 0,
                    preloading: TRUE,
                    current: lang.transl('COLORBOX_OUTOF'),
                    previous: lang.transl('COLORBOX_PREV'),
                    next: lang.transl('COLORBOX_NEXT'),
                    close: lang.transl('COLORBOX_CLOSE'),
                    open: FALSE,
                    overlayClose: TRUE,

                    slideshow: FALSE,
                    slideshowAuto: TRUE,
                    slideshowSpeed: 2500,
                    slideshowStart: lang.transl('COLORBOX_START'),
                    slideshowStop: lang.transl('COLORBOX_STOP'),

                    onOpen: FALSE,
                    onLoad: FALSE,
                    onComplete: FALSE,
                    onCleanup: FALSE,
                    onClosed: FALSE
            };

            // ****************
            // HELPER FUNCTIONS
            // ****************

            // Convert % values to pixels
            function setSize(size, dimension) {
                    dimension = dimension === 'x' ? $window.width() : $window.height();//document.documentElement.clientWidth : document.documentElement.clientHeight;
                    return (typeof size === 'string') ? Math.round((size.match(/%/) ? (dimension / 100) * parseInt(size, 10) : parseInt(size, 10))) : size;
            }

            // Checks an href to see if it is a photo.
            // There is a force photo option (photo: true) for hrefs that cannot be matched by this regex.
            function isImage(url) {
                    url = $.isFunction(url) ? url.call(element) : url;
                    return settings.photo || url.match(/\.(gif|png|jpg|jpeg|bmp)(?:\?([^#]*))?(?:#(\.*))?$/i);
            }

            // Assigns functions results to their respective settings.  This allows functions to be used to set ColorBox options.
            function process() {
                    for (var i in settings) {
                            if ($.isFunction(settings[i]) && i.substring(0, 2) !== 'on') { // checks to make sure the function isn't one of the callbacks, they will be handled at the appropriate time.
                                settings[i] = settings[i].call(element);
                            }
                    }
                    settings.rel = settings.rel || element.rel;
                    settings.href = settings.href || element.href;
                    settings.title = settings.title || element.title;
            }

            function launch(elem) {

                    element = elem;

                    settings = $.extend({}, $(element).data(colorbox));

                    process(); // Convert functions to their returned values.

                    if (settings.rel && settings.rel !== 'nofollow') {
                            $related = $('.cboxElement').filter(function () {
                                    var relRelated = $(this).data(colorbox).rel || this.rel;
                                    return (relRelated === settings.rel);
                            });
                            index = $related.index(element);

                            // Check direct calls to ColorBox.
                            if (index < 0) {
                                    $related = $related.add(element);
                                    index = $related.length - 1;
                            }
                    } else {
                            $related = $(element);
                            index = 0;
                    }

                    if (!open) {
                            open = TRUE;

                            active = TRUE; // Prevents the page-change action from queuing up if the visitor holds down the left or right keys.

                            bookmark = element;

                            bookmark.blur(); // Remove the focus from the calling element.

                            // Set Navigation Key Bindings
                            $(document).bind("keydown.cbox_close", function (e) {
                                    if (e.keyCode === 27) {
                                            e.preventDefault();
                                            cboxPublic.close();
                                    }
                            }).bind("keydown.cbox_arrows", function (e) {
                                    if ($related.length > 1) {
                                            if (e.keyCode === 37) {
                                                    e.preventDefault();
                                                    $prev.click();
                                            } else if (e.keyCode === 39) {
                                                    e.preventDefault();
                                                    $next.click();
                                            }
                                    }
                            });

                            if (settings.overlayClose) {
                                    $overlay.css({"cursor": "pointer"}).one('click', cboxPublic.close);
                            }

                            $.event.trigger(cbox_open);
                            if (settings.onOpen) {
                                    settings.onOpen.call(element);
                            }

                            $overlay.css({"opacity": settings.opacity}).show();

                            // Opens inital empty ColorBox prior to content being loaded.
                            settings.w = setSize(settings.initialWidth, 'x');
                            settings.h = setSize(settings.initialHeight, 'y');
                            cboxPublic.position(0);

                            if (isIE6) {
                                    $window.bind('resize.cboxie6 scroll.cboxie6', function () {
                                            $overlay.css({width: $window.width(), height: $window.height(), top: $window.scrollTop(), left: $window.scrollLeft()});
                                    }).trigger("scroll.cboxie6");
                            }
                    }

                    $current.add($prev).add($next).add($slideshow).add($title).hide();

                    $close.html(settings.close).show();

                    cboxPublic.slideshow();

                    cboxPublic.load();
            }

            // ****************
            // PUBLIC FUNCTIONS
            // Usage format: $.fn.colorbox.close();
            // Usage from within an iframe: parent.$.fn.colorbox.close();
            // ****************

            cboxPublic = $.fn.colorbox = function (options, callback) {
                    var $this = this;

                    if (!$this.length) {
                            if ($this.selector === '') { // empty selector means a direct call, ie: $.fn.colorbox();
                                    $this = $('<a/>');
                                    options.open = TRUE;
                            } else { // else the selector didn't match anything, and colorbox should go ahead and return.
                                    return this;
                            }
                    }

                    $this.each(function () {
                            var data = $.extend({}, $(this).data(colorbox) ? $(this).data(colorbox) : defaults, options);

                            $(this).data(colorbox, data).addClass("cboxElement");

                            if (callback) {
                                    $(this).data(colorbox).onComplete = callback;
                            }
                    });

                    if (options && options.open) {
                            launch($this);
                    }

                    return this;
            };

            // Initialize ColorBox: store common calculations, preload the interface graphics, append the html.
            // This preps colorbox for a speedy open when clicked, and lightens the burdon on the browser by only
            // having to run once, instead of each time colorbox is opened.
            cboxPublic.init = function () {

                    // jQuery object generator to save a bit of space
                    function $div(id) {
                            return $('<div id="cbox' + id + '"/>');
                    }

                    // Create & Append jQuery Objects
                    $window = $(window);
                    $cbox = $('<div id="colorbox"/>');
                    $overlay = $div("Overlay").hide();
                    $wrap = $div("Wrapper");
                    $content = $div("Content").append(
                            $loaded = $div("LoadedContent").css({width: 0, height: 0}),
                            $loadingOverlay = $div("LoadingOverlay"),
                            $loadingGraphic = $div("LoadingGraphic"),
                            $title = $div("Title"),
                            $current = $div("Current"),
                            $slideshow = $div("Slideshow"),
                            $next = $div("Next"),
                            $prev = $div("Previous"),
                            $close = $div("Close")
                    );
                    $wrap.append( // The 3x3 Grid that makes up ColorBox
                            $('<div/>').append(
                                    $div("TopLeft"),
                                    $topBorder = $div("TopCenter"),
                                    $div("TopRight")
                            ),
                            $('<div/>').append(
                                    $leftBorder = $div("MiddleLeft"),
                                    $content,
                                    $rightBorder = $div("MiddleRight")
                            ),
                            $('<div/>').append(
                                    $div("BottomLeft"),
                                    $bottomBorder = $div("BottomCenter"),
                                    $div("BottomRight")
                            )
                    ).children().children().css({'float': 'left'});

                    $loadingBay = $("<div style='position:absolute; top:0; left:0; width:9999px; height:0;'/>");

                    $('body').prepend($overlay, $cbox.append($wrap, $loadingBay));

                    if (isIE) {
                            $cbox.addClass('cboxIE');
                            if (isIE6) {
                                    $overlay.css('position', 'absolute');
                            }
                    }

                    // Add rollover event to navigation elements
                    $content.children()
                    .bind('mouseover mouseout', function(){
                            $(this).toggleClass(hover);
                    }).addClass(hover);

                    // Cache values needed for size calculations
                    interfaceHeight = $topBorder.height() + $bottomBorder.height() + $content.outerHeight(TRUE) - $content.height();//Subtraction needed for IE6
                    interfaceWidth = $leftBorder.width() + $rightBorder.width() + $content.outerWidth(TRUE) - $content.width();
                    loadedHeight = $loaded.outerHeight(TRUE);
                    loadedWidth = $loaded.outerWidth(TRUE);

                    // Setting padding to remove the need to do size conversions during the animation step.
                    $cbox.css({"padding-bottom": interfaceHeight, "padding-right": interfaceWidth}).hide();

                    // Setup button & key events.
                    $next.click(cboxPublic.next);
                    $prev.click(cboxPublic.prev);
                    $close.click(cboxPublic.close);

                    // Adding the 'hover' class allowed the browser to load the hover-state
                    // background graphics.  The class can now can be removed.
                    $content.children().removeClass(hover);

                    $('.cboxElement').live('click', function (e) {
                            if (e.button !== 0 && typeof e.button !== 'undefined') {// checks to see if it was a non-left mouse-click.
                                    return TRUE;
                            } else {
                                    launch(this);
                                    return FALSE;
                            }
                    });
            };

            cboxPublic.position = function (speed, loadedCallback) {
                    var
                    animate_speed,
                    winHeight = $window.height(),
                    // keeps the top and left positions within the browser's viewport.
                    posTop = Math.max(winHeight - settings.h - loadedHeight - interfaceHeight,0)/2 + $window.scrollTop(),
                    posLeft = Math.max(document.documentElement.clientWidth - settings.w - loadedWidth - interfaceWidth,0)/2 + $window.scrollLeft();

                    // setting the speed to 0 to reduce the delay between same-sized content.
                    animate_speed = ($cbox.width() === settings.w+loadedWidth && $cbox.height() === settings.h+loadedHeight) ? 0 : speed;

                    // this gives the wrapper plenty of breathing room so it's floated contents can move around smoothly,
                    // but it has to be shrank down around the size of div#colorbox when it's done.  If not,
                    // it can invoke an obscure IE bug when using iframes.
                    $wrap[0].style.width = $wrap[0].style.height = "9999px";

                    function modalDimensions (that) {
                            // loading overlay size has to be sure that IE6 uses the correct height.
                            $topBorder[0].style.width = $bottomBorder[0].style.width = $content[0].style.width = that.style.width;
                            $loadingGraphic[0].style.height = $loadingOverlay[0].style.height = $content[0].style.height = $leftBorder[0].style.height = $rightBorder[0].style.height = that.style.height;
                    }

                    $cbox.dequeue().animate({width:settings.w+loadedWidth, height:settings.h+loadedHeight, top:posTop, left:posLeft}, {duration: animate_speed,
                            complete: function(){
                                    modalDimensions(this);

                                    active = FALSE;

                                    // shrink the wrapper down to exactly the size of colorbox to avoid a bug in IE's iframe implementation.
                                    $wrap[0].style.width = (settings.w+loadedWidth+interfaceWidth) + "px";
                                    $wrap[0].style.height = (settings.h+loadedHeight+interfaceHeight) + "px";

                                    if (loadedCallback) {loadedCallback();}
                            },
                            step: function(){
                                    modalDimensions(this);
                            }
                    });
            };

            cboxPublic.resize = function (object) {
                    if(!open){return;}

                    var topMargin,
                    prev,
                    prevSrc,
                    next,
                    nextSrc,
                    photo,
                    timeout,
                    speed = settings.transition==="none" ? 0 : settings.speed;

                    $window.unbind(cbox_resize);

                    if(!object){
                            timeout = setTimeout(function(){ // timer allows IE to render the dimensions before attempting to calculate the height
                                    var $child = $loaded.wrapInner("<div style='overflow:auto'></div>").children(); // temporary wrapper to get an accurate estimate of just how high the total content should be.
                                    settings.h = $child.height();
                                    $loaded.css({height:settings.h});
                                    $child.replaceWith($child.children()); // ditch the temporary wrapper div used in height calculation
                                    cboxPublic.position(speed);
                            }, 1);
                            return;
                    }

                    $loaded.remove();
                    $loaded = $('<div id="cboxLoadedContent"/>').html(object);

                    function getWidth(){
                            settings.w = settings.w || $loaded.width();
                            settings.w = settings.mw && settings.mw < settings.w ? settings.mw : settings.w;
                            return settings.w;
                    }
                    function getHeight(){
                            settings.h = settings.h || $loaded.height();
                            settings.h = settings.mh && settings.mh < settings.h ? settings.mh : settings.h;
                            return settings.h;
                    }

                    $loaded.hide()
                    .appendTo($loadingBay)// content has to be appended to the DOM for accurate size calculations.  Appended to an absolutely positioned element, rather than BODY, which avoids an extremely brief display of the vertical scrollbar in Firefox that can occur for a small minority of websites.
                    .css({width:getWidth(), overflow:settings.scrolling ? 'auto' : 'hidden'})
                    .css({height:getHeight()})// sets the height independently from the width in case the new width influences the value of height.
                    .prependTo($content);

                    $('#cboxPhoto').css({cssFloat:'none'});// floating the IMG removes the bottom line-height and fixed a problem where IE miscalculates the width of the parent element as 100% of the document width.

                    // Hides SELECT elements in IE6 because they would otherwise sit on top of the overlay.
                    if (isIE6) {
                            $('select:not(#colorbox select)').filter(function(){
                                    return this.style.visibility !== 'hidden';
                            }).css({'visibility':'hidden'}).one(cbox_cleanup, function(){
                                    this.style.visibility = 'inherit';
                            });
                    }

                    function setPosition (s) {
                            cboxPublic.position(s, function(){
                                    if (!open) {return;}

                                    if (isIE) {
                                            //This fadeIn helps the bicubic resampling to kick-in.
                                            if( photo ){$loaded.fadeIn(100);}
                                            //IE adds a filter when ColorBox fades in and out that can cause problems if the loaded content contains transparent pngs.
                                            $cbox[0].style.removeAttribute("filter");
                                    }

                                    //Waited until the iframe is added to the DOM & it is visible before setting the src.
                                    //This increases compatability with pages using DOM dependent JavaScript.
                                    if(settings.iframe){
                                            $loaded.append("<iframe id='cboxIframe'" + (settings.scrolling ? " " : "scrolling='no'") + " name='iframe_"+new Date().getTime()+"' frameborder=0 src='"+settings.href+"' " + (isIE ? "allowtransparency='true'" : '') + " />");
                                    }

                                    $loaded.show();

                                    $title.show().html(settings.title);

                                    if ($related.length>1) {
                                            $current.html(settings.current.replace(/\{current\}/, index+1).replace(/\{total\}/, $related.length)).show();
                                            $next.html(settings.next).show();
                                            $prev.html(settings.previous).show();

                                            if(settings.slideshow){
                                                    $slideshow.show();
                                            }
                                    }

                                    $loadingOverlay.hide();
                                    $loadingGraphic.hide();

                                    $.event.trigger(cbox_complete);
                                    if (settings.onComplete) {
                                            settings.onComplete.call(element);
                                    }

                                    if (settings.transition === 'fade'){
                                            $cbox.fadeTo(speed, 1, function(){
                                                    if(isIE){$cbox[0].style.removeAttribute("filter");}
                                            });
                                    }

                                    $window.bind(cbox_resize, function(){
                                            cboxPublic.position(0);
                                    });
                            });
                    }

                    if((settings.transition === 'fade' && $cbox.fadeTo(speed, 0, function(){setPosition(0);})) || setPosition(speed)){}

                    // Preloads images within a rel group
                    if (settings.preloading && $related.length>1) {
                            prev = index > 0 ? $related[index-1] : $related[$related.length-1];
                            next = index < $related.length-1 ? $related[index+1] : $related[0];
                            nextSrc = $(next).data(colorbox).href || next.href;
                            prevSrc = $(prev).data(colorbox).href || prev.href;

                            if(isImage(nextSrc)){
                                    $('<img />').attr('src', nextSrc);
                            }

                            if(isImage(prevSrc)){
                                    $('<img />').attr('src', prevSrc);
                            }
                    }
            };

            cboxPublic.load = function () {
                    var href, img, setResize, resize = cboxPublic.resize;

                    active = TRUE;
                    element = $related[index];

                    settings = $.extend({}, $(element).data(colorbox));

                    //convert functions to static values
                    process();

                    $.event.trigger(cbox_load);
                    if (settings.onLoad) {
                            settings.onLoad.call(element);
                    }

                    // Evaluate the height based on the optional height and width settings.
                    settings.h = settings.height ?
                                    setSize(settings.height, 'y') - loadedHeight - interfaceHeight :
                                    settings.innerHeight ?
                                            setSize(settings.innerHeight, 'y') :
                                            FALSE;
                    settings.w = settings.width ?
                                    setSize(settings.width, 'x') - loadedWidth - interfaceWidth :
                                    settings.innerWidth ?
                                            setSize(settings.innerWidth, 'x') :
                                            FALSE;

                    // Sets the minimum dimensions for use in image scaling
                    settings.mw = settings.w;
                    settings.mh = settings.h;

                    // Re-evaluate the minimum width and height based on maxWidth and maxHeight values.
                    // If the width or height exceed the maxWidth or maxHeight, use the maximum values instead.
                    if(settings.maxWidth){
                            settings.mw = setSize(settings.maxWidth, 'x') - loadedWidth - interfaceWidth;
                            settings.mw = settings.w && settings.w < settings.mw ? settings.w : settings.mw;
                    }
                    if(settings.maxHeight){
                            settings.mh = setSize(settings.maxHeight, 'y') - loadedHeight - interfaceHeight;
                            settings.mh = settings.h && settings.h < settings.mh ? settings.h : settings.mh;
                    }

                    href = settings.href;

                    $loadingOverlay.show();
                    $loadingGraphic.show();

                    if (settings.inline) {
                            // Inserts an empty placeholder where inline content is being pulled from.
                            // An event is bound to put inline content back when ColorBox closes or loads new content.
                            $('<div id="cboxInlineTemp" />').hide().insertBefore($(href)[0]).bind(cbox_load+' '+cbox_cleanup, function(){
                                    $(this).replaceWith($loaded.children());
                            });
                            resize($(href));
                    } else if (settings.iframe) {
                            // IFrame element won't be added to the DOM until it is ready to be displayed,
                            // to avoid problems with DOM-ready JS that might be trying to run in that iframe.
                            resize(" ");
                    } else if (settings.html) {
                            resize(settings.html);
                    } else if (isImage(href)){
                            img = new Image();
                            img.onload = function(){
                                    var percent;

                                    img.onload = null;

                                    img.id = 'cboxPhoto';

                                    $(img).css({margin:'auto', border:'none', display:'block', cssFloat:'left'});

                                    if(settings.scalePhotos){
                                            setResize = function(){
                                                    img.height -= img.height * percent;
                                                    img.width -= img.width * percent;
                                            };
                                            if(settings.mw && img.width > settings.mw){
                                                    percent = (img.width - settings.mw) / img.width;
                                                    setResize();
                                            }
                                            if(settings.mh && img.height > settings.mh){
                                                    percent = (img.height - settings.mh) / img.height;
                                                    setResize();
                                            }
                                    }

                                    if (settings.h) {
                                            img.style.marginTop = Math.max(settings.h - img.height,0)/2 + 'px';
                                    }

                                    resize(img);

                                    if($related.length > 1){
                                            $(img).css({cursor:'pointer'}).click(cboxPublic.next);
                                    }

                                    if(isIE){
                                            img.style.msInterpolationMode='bicubic';
                                    }
                            };
                            img.src = href;
                    } else {
                            $('<div />').appendTo($loadingBay).load(href, function(data, textStatus){
                                    if(textStatus === "success"){
                                            resize(this);
                                    } else {
                                            resize($("<p>Request unsuccessful.</p>"));
                                    }
                            });
                    }
            };

            // Navigates to the next page/image in a set.
            cboxPublic.next = function () {
                    if(!active){
                            index = index < $related.length-1 ? index+1 : 0;
                            cboxPublic.load();
                    }
            };

            cboxPublic.prev = function () {
                    if(!active){
                            index = index > 0 ? index-1 : $related.length-1;
                            cboxPublic.load();
                    }
            };

            cboxPublic.slideshow = function () {
                    var stop, timeOut, className = 'cboxSlideshow_';

                    $slideshow.bind(cbox_closed, function(){
                            $slideshow.unbind();
                            clearTimeout(timeOut);
                            $cbox.removeClass(className+"off"+" "+className+"on");
                    });

                    function start(){
                            $slideshow
                            .text(settings.slideshowStop)
                            .bind(cbox_complete, function(){
                                    timeOut = setTimeout(cboxPublic.next, settings.slideshowSpeed);
                            })
                            .bind(cbox_load, function(){
                                    clearTimeout(timeOut);
                            }).one("click", function(){
                                    stop();
                                    $(this).removeClass(hover);
                            });
                            $cbox.removeClass(className+"off").addClass(className+"on");
                    }

                    stop = function(){
                            clearTimeout(timeOut);
                            $slideshow
                            .text(settings.slideshowStart)
                            .unbind(cbox_complete+' '+cbox_load)
                            .one("click", function(){
                                    start();
                                    timeOut = setTimeout(cboxPublic.next, settings.slideshowSpeed);
                                    $(this).removeClass(hover);
                            });
                            $cbox.removeClass(className+"on").addClass(className+"off");
                    };

                    if(settings.slideshow && $related.length>1){
                            if(settings.slideshowAuto){
                                    start();
                            } else {
                                    stop();
                            }
                    }
            };

            // Note: to use this within an iframe use the following format: parent.$.fn.colorbox.close();
            cboxPublic.close = function () {

                    $.event.trigger(cbox_cleanup);
                    if (settings.onCleanup) {
                            settings.onCleanup.call(element);
                    }

                    open = FALSE;
                    $(document).unbind("keydown.cbox_close keydown.cbox_arrows");
                    $window.unbind(cbox_resize+' resize.cboxie6 scroll.cboxie6');
                    $overlay.css({cursor: 'auto'}).fadeOut('fast');

                    $cbox
                    .stop(TRUE, FALSE)
                    .fadeOut('fast', function () {
                            $('#colorbox iframe').attr('src', 'about:blank');
                            $loaded.remove();
                            $cbox.css({'opacity': 1});

                            try{
                                    bookmark.focus();
                            } catch (er){
                                    // do nothing
                            }

                            $.event.trigger(cbox_closed);
                            if (settings.onClosed) {
                                    settings.onClosed.call(element);
                            }
                    });
            };

            // A method for fetching the current element ColorBox is referencing.
            // returns a jQuery object.
            cboxPublic.element = function(){return $(element);};

            cboxPublic.settings = defaults;

            // Initializes ColorBox when the DOM has loaded
            $(cboxPublic.init);

    }(jQuery));


}



