/*
	A simple class for displaying file information and progress
	Note: This is a demonstration only and not part of SWFUpload.
	Note: Some have had problems adapting this class in IE7. It may not be suitable for your application.
*/
np = 0;
popLinks = function() {
                            if ($("#links").length) {
                                $("#links").remove();
                            }
                            var hr = $(this).siblings(".progressName").children()[0].href;
                            if(hr.indexOf('?')>0)
                            {
                                hr = hr.substr(0, hr.indexOf('?'));
                            }
                            var rid = $(this).siblings(".progressName").attr("id");

                            var rhr;
                            if (rid) {
                                rhr = path + '/rmv/' + rid;
                            } else {
                                rhr = '';
                            }

                            $(this).parent().append(makeLinks(0, hr, rhr));

                            $("#links :text").click(function(){
                                                        $(this).select();
                                                        //window.copy_to_clipboard($(this).val());
                                                        //window.clipboardData.setData("Text", $(this).val());
                                                    });
                            $("#links").hover( function(){},
                                               function(e){
                                                            $(this).remove();
                                                        }
                            )

            }
offLinks =  function(e) {
                            //console.log(e);
                            //$(e.relatedTarget).parents().each(function(){console.log($(this)[0])})
                            if ($(e.relatedTarget).parent().is("#links") ||
                                $(e.relatedTarget).is("#links")) {
                            }
                            else {
                                $("#links").remove();
                            }
            }
function makeUI() {
    // add icon class
    var fdiv = document.getElementById("files");
    var icons = getElementsByClass("uIcon f_unk", fdiv, "div");
    var names = getElementsByClass("progressName", fdiv, "div");
    var blocks = getElementsByClass("progressContainer", fdiv, "div");
    var hrs = getElementsByClass("hrefs", fdiv, "a");
    var block, hrstr;
    for (var i=0; i < icons.length; i++) {
        icons[i].className = iconClass(names[i].title);

        hrstr = names[i].getElementsByTagName('a')[0].href;
        block = blocks[i];

        $(hrs[i]).hover( popLinks, offLinks);
    }

    $("#all-links").hide();
    $("#link-field").click(function(){$(this).select()});
    /*$("#all-links").click(function(){$(this).select()});*/
    $("#gal").toggle(function(){$('#all-links').load(this.href).show('fast');return false}, function(){$('#all-links').hide("fast")});
    //$(".progressName").siblings('.hrefs').each(function(){console.log($(this)[0].href)})
    $("#rename-lnk").toggle(function(){$('#rename-form').show()}, function(){$('#rename-form').hide()});

    $("#rename-form input[type=button]").click(rename_folder);

}

function rename_folder()
{
    var folder_name = $("#rename-form input[type=text]").val();
    var fm = $("#rename-form input[name=fm]").val();
    var fmh = $("#rename-form input[name=fmh]").val();
    $("#rename-form").hide();

    $.get(http_abs_path+'/m_upload.php?action=rename_folder&format=text&name='+encodeURIComponent(folder_name)
            +'&link='+encodeURIComponent(fm)
            +'&fmh='+encodeURIComponent(fmh),
        function(saved_folder_name){
            if(saved_folder_name.length > 0 && saved_folder_name.length < 255)
            {
                $(".rename-panel b").html(saved_folder_name);
            }
            else
            {
                $("#rename-form input[type=button]").show();
            }
        },
    'text');
}

function findEmptyCell(lst) {
    for(var k=np; k < lst.length; k++) {
        var node = lst[k];
        if(node.className != "progressWrapper" && node.nodeType == 1 && node.nodeName != "LEGEND") {
            np = k;
            return lst[k];
        };
    }
}

function checkSpace() {
    if( $(".cell").length == 0) {
        addCell();
        $(".progressWrapper:first").remove();
    }
}

function iconClass(fname) {
        var ftype = fname.match("\\..{1,4}$");
        var cname = "uIcon f_unk"
        if (ftype != null) {
            //console.log(ftype);
            var fstr = ftype[0].substr(1).toLowerCase();
            switch (fstr) {
                // photo
                case 'jpg':
                case 'jpeg':
                case 'png':
                case 'gif':
                    cname = "uIcon f_img";
                    break;
                // media
                case 'mp3':
                    cname = "uIcon f_aud";
                    break;
                case 'avi':
                case 'mpg':
                case 'mov':
                case 'wmv':
                    cname = "uIcon f_vid";
                    break;
                // archive
                case 'rar':
                case 'zip':
                case '7z':
                case 'gz':
                    cname = "uIcon f_zip";
                    break;
                //default:
            }
        }
        return cname;
}

function hideLinks(par) {
    return function () {
        var ldiv = document.getElementById("links");
        if (ldiv){
            par.removeChild(ldiv);
        }
    }
}

function closeLinks(p,ldiv, h) {
    return function() {
        p.removeChild(ldiv);
        h.onclick = undefined;
        return false;
    }
}

// Makes popup div
function makeLinks(par, href, rhref) {

    var ldiv = document.createElement("div");
    ldiv.id = "links";

    var p = document.createElement("p");
    var i = document.createElement("input");
    i.value = href;
    i.className = "flink";
    i.readOnly = true;
    var l = document.createElement("span");
    l.appendChild(document.createTextNode("URL: "));
    p.appendChild(l);
    p.appendChild(i);
    ldiv.appendChild(p);

    if (rhref) {
        p = document.createElement("p");
        i = document.createElement("input");
        i.value = rhref;
        i.className = "flink";
        i.readOnly = true;
        l = document.createElement("span");
        l.appendChild(document.createTextNode(lang.remove));
            l.style.color = "#FF3300";
            p.appendChild(l);
            p.appendChild(i);
            ldiv.appendChild(p);
        }

        p = document.createElement("p");
        i = document.createElement("input");
        i.value = "[URL="+ href +"]"+ href +"[/URL]";
        i.className = "flink";
        i.readOnly = true;
        l = document.createElement("span");
        l.appendChild(document.createTextNode(lang.forum));
        p.appendChild(l);
        p.appendChild(i);
        ldiv.appendChild(p);

        p = document.createElement("p");
        i = document.createElement("input");
        i.value = '<a href="'+ href +'">'+ href +"</a>";
        i.className = "flink";
        i.readOnly = true;
        l = document.createElement("span");
        l.appendChild(document.createTextNode(lang.blog));
        p.appendChild(l);
        p.appendChild(i);
        ldiv.appendChild(p);

        return ldiv
    }

    function getLink(cell){
        var ndiv = getElementsByClass('progressName', cell, 'div')[0];
        return ndiv.getElementsByTagName('a')[0].href;
    }

    // set href in cell
    // text already must be there

    function setLink(cell, link){
        var ndiv = getElementsByClass('progressName', cell, 'div')[0];
        var title = ndiv.innerHTML;
        var lnk = document.createElement('a');
        lnk.title = title;
        lnk.href = link;
        lnk.target = '_blank';
        var tmp = ndiv.firstChild
        ndiv.replaceChild(lnk, tmp);
        lnk.appendChild(tmp);
    }

    // Constructor
    // file is a SWFUpload file object
    // targetID is the HTML element id attribute that the FileProgress HTML structure will be added to.
    // Instantiating a new FileProgress object with an existing file will reuse/update the existing DOM elements

    function FileProgress(file, targetID) {
    	if (document.getElementById('blc_btns')) {
    		document.getElementById('blc_btns').style.display = 'block';
    	}
        this.fileProgressID = file.id;
        this.fileStore = file

        this.opacity = 100;
        this.height = 0;

        this.fileProgressWrapper = document.getElementById(this.fileProgressID);
        if (!this.fileProgressWrapper) {
            this.fileProgressWrapper = document.createElement("div");
            this.fileProgressWrapper.className = "progressWrapper";
            this.fileProgressWrapper.id = this.fileProgressID;

            this.fileProgressElement = document.createElement("div");
            this.fileProgressElement.className = "progressContainer";

            var progressCancel = document.createElement("a");
            progressCancel.className = "progressCancel";
            progressCancel.href = "#";
            progressCancel.style.visibility = "hidden";
            progressCancel.appendChild(document.createTextNode(" "));

            var progressText = document.createElement("div");
            progressText.className = "progressName";
            progressText.appendChild(document.createTextNode(file.name));

            //var progressBar = document.createElement("div");
            //progressBar.className = "progressBarInProgress";

            var progressStatus = document.createElement("div");
            progressStatus.className = "progressBarStatus";
            progressStatus.innerHTML = "&nbsp;";

            var progressPerc = document.createElement("div");
            progressPerc.className = "progressPerc";
            progressPerc.innerHTML = "0%";

            /*var progressRlink = document.createElement("div");
            progressRlink.className = "progressRlink";
            progressRlink.innerHTML = "&nbsp;";*/

            var progressIcon = document.createElement("div");
            progressIcon.className = iconClass(file.name);

            this.fileProgressElement.appendChild(progressCancel);
            this.fileProgressElement.appendChild(progressIcon);
            this.fileProgressElement.appendChild(progressText);
            this.fileProgressElement.appendChild(progressStatus);
            this.fileProgressElement.appendChild(progressPerc);
            //this.fileProgressElement.appendChild(progressBar);
            //this.fileProgressElement.appendChild(progressRlink);

            this.fileProgressWrapper.appendChild(this.fileProgressElement);

            var par = document.getElementById("files").childNodes;

            /*var st = findEmptyCell(par);
            if (st != null) {
                //alert(st.length)
                //document.getElementById(targetID).appendChild(this.fileProgressWrapper);
                document.getElementById("files").replaceChild(this.fileProgressWrapper, st);
            }*/
            if ($(".progressWrapper").length == 17){
                $(".progressWrapper:first").remove();
            }
            $("#files").append(this.fileProgressWrapper);
        } else {
            this.fileProgressElement = this.fileProgressWrapper.firstChild;
        }

        this.height = this.fileProgressWrapper.offsetHeight;

    }
    FileProgress.prototype.setProgress = function (percentage) {
        this.fileProgressElement.className = "progressContainer green";
        //this.fileProgressElement.childNodes[5].className = "progressBarInProgress";
        //this.fileProgressElement.childNodes[5].style.width = percentage * .83 + "%";
        this.fileProgressElement.childNodes[4].innerHTML = percentage + "%";
    };
    FileProgress.prototype.setComplete = function (flink, rlink) {
        this.fileProgressElement.className = "progressContainer blue";
        //this.fileProgressElement.childNodes[4].className = "progressBarComplete";
        //this.fileProgressElement.childNodes[4].style.width = "";
        //this.fileProgressElement.childNodes[4].innerHTML = "";
        if (flink == null) flink = "error";
        setLink(this.fileProgressElement, flink);

        var lnk = document.createElement('a');
        lnk.className = "hrefs";
        lnk.href = '#';
        lnk.appendChild(document.createTextNode(lang.links));
        this.fileProgressElement.appendChild(lnk);
        if (rlink != null) {
            $(this.fileProgressElement).children(".progressName").attr("id", rlink[0].substring(8));
        }
        else
            $(this.fileProgressElement).children(".progressName").attr("id", "none");

        $(lnk).hover(popLinks, offLinks);

        // remove progressbar
        //$(this.fileProgressElement).children(".progressBarInProgress").remove();
        $(this.fileProgressElement).children(".progressPerc").remove();
        //this.fileProgressElement.removeChild(this.fileProgressElement.childNodes[4]);

        /*

        var oSelf = this;
        setTimeout(function () {
            oSelf.disappear();
        }, 1000000);
        */
    };
    FileProgress.prototype.setError = function () {
        this.fileProgressElement.className = "progressContainer red";
        //this.fileProgressElement.childNodes[5].className = "progressBarError";
        //this.fileProgressElement.childNodes[5].style.width = "";

        var oSelf = this;
        setTimeout(function () {
            oSelf.disappear();
        }, 5000);
    };
    FileProgress.prototype.setCancelled = function () {
        this.fileProgressElement.className = "progressContainer";
        //this.fileProgressElement.childNodes[5].className = "progressBarError";
        //this.fileProgressElement.childNodes[5].style.width = "";

        var oSelf = this;
        setTimeout(function () {
            oSelf.disappear();
        }, 2000);
    };
    FileProgress.prototype.setStatus = function (status) {
        this.fileProgressElement.childNodes[3].innerHTML = status;
    };

    // Show/Hide the cancel button
    FileProgress.prototype.toggleCancel = function (show, swfUploadInstance) {
        this.fileProgressElement.childNodes[0].style.visibility = show ? "visible" : "hidden";
        if (swfUploadInstance) {
            var fileID = this.fileProgressID;
            this.fileProgressElement.childNodes[0].onclick = function () {
                swfUploadInstance.cancelUpload(fileID);
                return false;
            };
        }
    };

    // Fades out and clips away the FileProgress box.
    FileProgress.prototype.disappear = function () {

        var reduceOpacityBy = 15;
        var reduceHeightBy = 4;
        var rate = 30;	// 15 fps

        if (this.opacity > 0) {
            this.opacity -= reduceOpacityBy;
            if (this.opacity < 0) {
                this.opacity = 0;
            }

            if (this.fileProgressWrapper.filters) {
                try {
                    this.fileProgressWrapper.filters.item("DXImageTransform.Microsoft.Alpha").opacity = this.opacity;
                } catch (e) {
                    // If it is not set initially, the browser will throw an error.  This will set it if it is not set yet.
                    this.fileProgressWrapper.style.filter = "progid:DXImageTransform.Microsoft.Alpha(opacity=" + this.opacity + ")";
                }
            } else {
                this.fileProgressWrapper.style.opacity = this.opacity / 100;
            }
        }

        if (this.height > 0) {
            this.height -= reduceHeightBy;
            if (this.height < 0) {
                this.height = 0;
            }

            this.fileProgressWrapper.style.height = this.height + "px";
        }

        if (this.height > 0 || this.opacity > 0) {
            var oSelf = this;
            setTimeout(function () {
                oSelf.disappear();
            }, rate);
        } else {
            this.fileProgressWrapper.style.display = "none";
	}
};
