/**

filestyle.js
 */
/*
 * Style File - jQuery plugin for styling file input elements
 *
 * Copyright (c) 2007-2009 Mika Tuupola
 *
 * Licensed under the MIT license:
 *   http://www.opensource.org/licenses/mit-license.php
 *
 * Based on work by Shaun Inman
 *   http://www.shauninman.com/archive/2007/09/10/styling_file_inputs_with_css_and_the_dom
 *
 */

(function($) {

    $.fn.filestyle = function(options) {

        /* TODO: This should not override CSS. */
        var settings = {
            width : 250
        };

        if(options) {
            $.extend(settings, options);
        };

        return this.each(function() {

            var self = this;
            var wrapper = $("<div>")
                            .css({
                                "width": settings.imagewidth + "px",
                                "height": settings.imageheight + "px",
                                "background": "url(" + settings.image + ") 0 0 no-repeat",
                                "background-position": "right",
                                "display": "inline",
                                "position": "absolute",
                                "overflow": "hidden"
                            });

            var filename = $('<input class="file">')
                             .addClass($(self).attr("class"))
                             .css({
				"display": "inline",
                                 "width": settings.width + "px"
                             });

            $(self).before(filename);
            $(self).wrap(wrapper);

            $(self).css({
                        "position": "relative",
                        "height": settings.imageheight + "px",
                        "width": settings.width + "px",
                        "display": "inline",
                        "cursor": "pointer" ,
                        "opacity": "0.0"
                    });

            if ($.browser.mozilla) {
                if (/Win/.test(navigator.platform)) {
                    $(self).css("margin-left", "-142px");
                } else {
                    $(self).css("margin-left", "-168px");
                };
            } else {
                $(self).css("margin-left", settings.imagewidth - settings.width + "px");
            };

            $(self).bind("change", function() {
                filename.val($(self).val());
            });

        });


    };

})(jQuery);


/**
jqueryprogressbar.js
 */
/*
 * Copyright (c) 2007 Josh Bush (digitalbush.com)
 *
 * Permission is hereby granted, free of charge, to any person
 * obtaining a copy of this software and associated documentation
 * files (the "Software"), to deal in the Software without
 * restriction, including without limitation the rights to use,
 * copy, modify, merge, publish, distribute, sublicense, and/or sell
 * copies of the Software, and to permit persons to whom the
 * Software is furnished to do so, subject to the following
 * conditions:

 * The above copyright notice and this permission notice shall be
 * included in all copies or substantial portions of the Software.
 *
 * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
 * EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES
 * OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
 * NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT
 * HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY,
 * WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
 * FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR
 * OTHER DEALINGS IN THE SOFTWARE.
 */

/*
 * Progress Bar Plugin for jQuery
 * Version: Alpha 2
 * Release: 2007-02-26
 */
(function($) {
	//Main Method
	$.fn.reportprogress = function(val,maxVal) {
		var max=100;
		if(maxVal)
			max=maxVal;
		return this.each(
			function(){
				var div=$(this);
				var innerdiv=div.find(".progress");

				if(innerdiv.length!=1){
					innerdiv=$("<div class='progress'></div>");
					div.append("<div class='text'>&nbsp;</div>");
					$("<span class='text'>&nbsp;</span>").css("width",div.width()).appendTo(innerdiv);
					div.append(innerdiv);
				}
				var width=Math.round(val/max*100);
				innerdiv.css("width", width+"%");
				div.find(".text").html(width+" %");
			}
		);
	};
})(jQuery);


/**
multiUpload.js
 */
var	timer = 3000,
	disallowExtension = '(sh|php|php3|php4|php5|py|shtml|stm|shtm|phtml|html|htm|js|jsp|asp|aspx|cgi|pl|plx|htaccess|htpasswd)',
	startTime = null,
	fileList = [],
	currentUploadIndex = 0,
	numOfUploadFile = 1,
	uploadedCount = 0,
	numOfValidFile = 0,
	$iframe =null,
	count = 0;

var getFileExtension = function(filename){
    var file_extension = filename.substring(filename.lastIndexOf('.') + 1, filename.length).toLowerCase();
    return file_extension;
};

var getFileName = function(filename){
    var file_name = filename.substring(filename.lastIndexOf('\\') + 1, filename.length);
    return file_name;
};

var round = function(n) {
    return Math.round(n / 1024 / 1024 * 10) / 10;
};

function setFile(){
	while(currentUploadIndex<=numOfUploadFile){
		currentUploadIndex++;
		var $ref=$("#file" + currentUploadIndex);
		var filename = $ref.val();
		if(currentUploadIndex<=numOfUploadFile && filename !="" && typeof filename!== "undefined"){
	        $('#file').replaceWith($ref);
	        $ref.attr('id', 'file');
	        $ref.data('updateIndex', currentUploadIndex);
	        fileList.currentUpload=$ref;
	        return true;
	    }
	}
	fileList.currentUpload=null;
	return false;
};

function validateUploadForm(){
	if($("#tncCheckbox").attr('checked')){
		numOfValidFile=0;
		for (i=1;i<=numOfUploadFile;i++){
			var filename = $("#file" + i).val();
			if(filename!='' && typeof filename!== "undefined")
				numOfValidFile++;
			}
			if(numOfValidFile>0)
				return true;
			else
				alert('Please select a file');
	}else{
		alert('You must check the box to agree with our upload terms and conditions');
	}
	return false;
};

function formatSize(l){
	if(l < 1024)
		return l+" Bytes";
	l = l/1024;
	if(l < 1024)
		return (Math.floor(l*100)/100)+" KB";
	l = l/1024;
	if(l < 1024)
		return (Math.floor(l*100)/100)+" MB";
	l = l/1024;
	return (Math.floor(l*100)/100)+" GB";
}

function replacePlaceHolder(template, json){
	template=template.replace(/{shorten}/i, json.shortenCode);
	template=template.replace(/{name}/i, json.fileName);
	template=template.replace(/{size}/i, formatSize(json.fileSize));
	return template;
}

function uploadFinish(json) {
	if(json!=null){
		$("#progressbar").reportprogress(100);
		var oldStatus=fileList.currentUpload.data('status');
		var newStatus=$(replacePlaceHolder( $('#uploadedTemplate').html(), json));
		oldStatus.replaceWith(newStatus);
		fileList.currentUpload.data('status', newStatus);
		var plainLink=replacePlaceHolder(downloadUrl+"/file/{shorten}/{name}", json);
		var plainDeleteLink=replacePlaceHolder(downloadUrl+"/file/{shorten}", json);
		$('#linkLinks'	).val($('#linkLinks'	).val()+plainLink+"\n");
		$('#forum1Links').val(replacePlaceHolder("[url="+plainLink+"][b]File name: {name} File size: {size}[/b][/url]\n", json));
		$('#forum2Links').val(replacePlaceHolder("<a href=\""+plainLink+"\"><b>File name: {name}<br />File size:{size}<br /></b></a><br />\n", json));
		$('#htmlLinks'	).val(replacePlaceHolder("<a href=\""+plainLink+"\">"+plainLink+"</a><br />\n", json));
		$('#deleteLinks').val($('#deleteLinks'	).val()+plainDeleteLink+"/delete/"+json.deleteCode+"\n");
	    $("<input />").attr({"name":"shortenCode[]","value":json.shortenCode,"type":"hidden"}).appendTo("#emailForm");
	    $("#site_icon a").each(function(){
	    	this.href = this.href.replace(/downloadUrl/i, plainLink);
	    });
	}
	uploadedCount++;	
	if (uploadedCount >= numOfValidFile){
		if($('#uploadedComplete').length>0){			
			count = 0;
			$('#middle, #uploadDiv').hide();
			// move the list
			$(".file_list .upload_fail").css('display','none');
			$(".file_list div").appendTo("#uploadedTXT");
			if(uploadedCount>0){
				$('#uploadedComplete .msgSingle').hide();
				$('#uploadedComplete .msgMulti').show();
			}else{
				$('#uploadedComplete .msgSingle').show();
				$('#uploadedComplete .msgMulti').hide();
			}
			if($.browser.msie){
				$('.copyLinkBtn').show().click(function(){
					copyClip($(this).prev('textarea').val());					
				});
			}else{
				$('.copyLinkBtn').hide();
			}
			$('#uploadedComplete').show();
//			$('#emailBtn').click(function(){
//					$('.email').show(); // email form section
//			});
			$('.sendDownloadLink').click(function(){
				$('#emailForm').submit();
			});
			
		}else{
			location.reload();
		}
	}
	
};

function uploadFail(file, msgType){
	clearTimeout(progressHandle);// clear if any
	file = getFileName(file);
	var $remindBox=$("#remindBox"),
		$remindMsg=$("#remindMsg_"+msgType);
	if($remindMsg.length==0){
		$remindMsg=$("#remindMsgFailed");
	}
	
	$(".fileChooser:eq("+(currentUploadIndex-1)+")").find(".loading_icon").attr('title', 'Fail');
    $(".fileChooser:eq("+(currentUploadIndex-1)+")").find(".loading_icon").attr('class', 'red_icon');
    
	var $content = $remindMsg.html().replace(/filename/i, file);
	$("#remindMsg").html($content);
	$remindBox.show();

	var oldStatus=fileList.currentUpload.data('status');
	if(oldStatus){
		var newStatus=$(replacePlaceHolder( $('#upload_failedTemplate').html(), {
			"fileName": file
		}));
		oldStatus.replaceWith(newStatus);
		fileList.currentUpload.data('status', newStatus);
	}
    numOfValidFile--;
}

var progressHandle,
	progressInterval=1000,
	progressTimeout=5000;

function progress() {
	clearTimeout(progressHandle); //always one chain
	if (arguments.length == 0) {
		progressHandle=setTimeout(function(){
			$.getJSON(origUploadUrl + "?sessionId="+jsUploadSessionId+"&callback=?", progress);
			// if it fail, re ask
			progressHandle=setTimeout(progress, progressTimeout);
		}, progressInterval);
        return;
	} else if (arguments[0] == 'now') {
		$.getJSON(origUploadUrl + "?sessionId="+jsUploadSessionId+"&callback=?", progress);
		return;
	}
	var json=arguments[0];
	if(!json)return;
	if(json.sessionId!=jsUploadSessionId){
		progress();
	}
	
    if (json.state == "done"){
        $("#progressbar").reportprogress(100);
        $("#status").html("");
        $('#status1').html("Uploaded!<br/><img src=\"/images/loading.gif\"/> Please wait while processing ... ");
        
        $(".fileChooser:eq("+(currentUploadIndex-1)+")").find(".loading_icon").attr('class', 'green_icon');
        $(".fileChooser:eq("+(currentUploadIndex-1)+")").find(".loading_icon").attr('title', 'Complete');
        
        uploadFinish(json);

		// start another file upload
        processNextUpload();
    }else if (json.state == "toolarge"){
        //uploadXHR.abort();
        uploadFail($("#file").val(), 'toolarge');
        // start another file upload
        processNextUpload();
    }else if (json.state == "uploading"){
    	var	percent = json.precent,
       		uploadStatus="uploading",
       		now = new Date(),
       		timeRemain = ((now - startTime)/percent*100-(now - startTime))/1000;
    	$("#progressbar").reportprogress(percent);
    	$("#status").html('<b> '+ percent + '%</b> ( ' +round(json.received) + ' MB of ' + round(json.size) + ' MB )');
    	if(percent!=0){
           if(timeRemain<60)
               uploadStatus = "Less than 1 minute remaining";
           else if(timeRemain<3600)
               uploadStatus = Math.ceil(timeRemain/60)+" minutes remaining";
           else
               uploadStatus = Math.floor(timeRemain/3600)+" hour(s) "+Math.round(timeRemain%3600/60)+" minute(s) remaining";
    	}
    	$('#status1').html(uploadStatus);
    	json.fileName = getFileName($("#file").val()); 
    	var oldStatus=fileList.currentUpload.data('status');
    	var newStatus=$(replacePlaceHolder( $('#upload_progessTemplate').html(), json));
    	oldStatus.replaceWith(newStatus);
    	fileList.currentUpload.data('status', newStatus);
    	progress();
    } else if (json.state == "error") {
		uploadFail($("#file").val(), json.msg);
        // start another file upload
        processNextUpload();
    } else {
    	progress();
    }
};

// start another file upload
function processNextUpload(){
    if(numOfValidFile==0){
        resetLayout();
    }else if(setFile()){
        uploadFile();
    }else{
    	uploadFinish(null);
    }
}

function submitUpload(){
	numOfUploadFile = $('input[name=file]').length-1-$('.fileChooser_temp').length;
    $("#progressbar").reportprogress(0);

//    $("#remindBox").hide().find("*").remove();
    
    //if checkbox not check or no file chosen, return
	if(!validateUploadForm())
		return false;

	//change the layout
	$("#multiUploadSubmitBtn")
		.attr("disabled", "true")
		.addClass('multiUploadSubmitBtnDisabled')
		.unbind('.upload');
    
	if(numOfValidFile<=1){
		$("#welcomeMsg, #submitUpload, #fileName").hide();
		$("#uploadingTxt").show();
	} else {
		$("#welcomeMsg, #fileName").hide();
		$("#uploadingTxt").show();
	}
	
//	$("#multiUploadSubmitBtn").attr("disabled", "true");
    if(numOfValidFile<=1)
      $("#submitUpload").hide();
    $("#.fileChooser div").removeAttr('style');
    $("#remindBox").hide();
    $("#uploadMore").hide();
    $("#uploading").show();
    $("#remindMsg").html('');
    for (i=1;i<=numOfUploadFile;i++){
    	if($("#file" + i).val()!=''){
    		$('#file' + i).before('<input type="text" name="textfield2" id="textfield" style="width:450px" disabled="disabled" value="'+$("#file" + i).val()+'"/><input name="" type="button" value="Browse..." disabled />');
            $(".fileChooser:eq("+(i-1)+")").find(".loading_icon").css('display', 'block');
    	}else{
    		$(".fileChooser:eq("+(i-1)+")").css('display', 'none');
    	}
    }
    $('.file').hide();
    // create uploading file name list
    for (i=1;i<=numOfUploadFile;i++){
    	var $ref=$("#file" + i),  n=getFileName($ref.val());
    	if(n!=''){
    		$('#file_list').hide();
    		var obj=$(replacePlaceHolder($('#upload_progessTemplate').html(), {
    			"fileName" : n
    		})).appendTo('#file_list');
    		fileList[fileList.length] = $ref;
    		$ref.data('status', obj);
    	}else{
    		$ref.closest('.fileChooser').remove();
    	}
    }
    clearResultForm();    
	
    $("#uploading").show();
	
    //start upload
    if(setFile(fileList))
    	uploadFile(fileList);
    return false;
}

function addMoreFileButton(){
    var $newUploadFile = $('.fileChooser_temp').clone();
    $newUploadFile.attr('class', 'fileChooser');
    $newUploadFile.find('input')
    	.addClass('file')
    	.attr('id', 'file' + ($('input[name=file]').length-$('.fileChooser_temp').length));
    if (navigator.userAgent.toLowerCase().indexOf("webkit") > 0) {
    	$newUploadFile.find("input")
    		.filestyle({ imageheight: 22, imagewidth: 110, width: 510, image: './images/file_input_browse.gif' });
    	$newUploadFile.children("td").css('text-indent', '-80px');
    	$('.upload_select').width(550);
    }
    $newUploadFile.insertBefore('#rowUploadMore').show();
    return false;
}

$(function(){
    if (navigator.userAgent.toLowerCase().indexOf("webkit") > 0) {
        $("input.file").filestyle({ imageheight: 22, imagewidth: 110, width: 510, image: './images/file_input_browse.gif' });
        $(".fileChooser").children("td").css('text-indent', '-80px');
        $('.upload_select').width(550);
    }
    
    $('#multiUploadSubmitBtn').bind('click.upload', submitUpload);
    $("#uploadMore").bind('click.upload', addMoreFileButton);
});

function clearResultForm(){
	$('#linkLinks'	).val('');
	$('#forum1Links').val('');
	$('#forum2Links').val('');
	$('#htmlLinks'	).val('');
	$('#deleteLinks').val('');
    $('#emailForm input[name="link[]"]').remove();
}

function resetLayout(){
	fileList = [];
	currentUploadIndex = 0;
	numOfUploadFile = 1;
	uploadedCount = 0;
	numOfValidFile = 0;

	clearResultForm();
	$('.fileChooser, .file_list *').remove();
    $("#uploading").hide();
    
	$("#multiUploadSubmitBtn")
	.removeAttr("disabled")
	.removeClass('multiUploadSubmitBtnDisabled')
	.bind('click.upload', submitUpload);
    addMoreFileButton();
    $('#submitUpload, #uploadMore, .file').show();
}

var origUploadUrl=null;
var jsUploadSessionId=null;
function uploadFile(){
	var $ref=fileList.currentUpload;
    if(getFileExtension($ref.val()).match(disallowExtension)){
    	uploadFail($ref.val(), 'file_ext');
        processNextUpload();
    } else {
        $("#fileName").text(getFileName($ref.val()));
        $("#fileName").show();
        $("#progressbar").reportprogress(0);
        if($iframe!=null){
        	$iframe.remove();
        }
        $iframe=$('<iframe name="upload_temp_iframe" src="javascript:void(1)"/>');
        $iframe
        	.css({ position: 'absolute', top: '-1000px', left: '-1000px', width:'1px', height:'1px' })
			.appendTo('body');
        startTime = new Date();
        
      	// prepare for the finish callback from iframe
        document.domain=downloadUrl.replace(/.+\.([^.]+?)\.([^.]+?)/,'$1.$2');
//        document.domain='fileserve.com';
        $iframe[0].progressCallback=progress;
        
        var $form=$('#uploadForm');
        $form[0].setAttribute('target', 'upload_temp_iframe');
        
        // initialize session
        if(origUploadUrl==null){
        	origUploadUrl=$form[0].getAttribute('action');
        }
        
        // Note: Jquery won't do error/timeout for JSONP!!! (up to 1.5.0)
        var timeoutHandle=setTimeout(function(){
        	timeoutHandle=null;
        	uploadFail($ref.val(), 'timeout');
        }, 5000);
        $.getJSON(origUploadUrl + "?callback=?", function(data) {
	    		if(timeoutHandle==null){
	    			return; // too late
	    		}
	    		clearTimeout(timeoutHandle);
				if(!data || data.state!='waiting'){
					uploadFail($ref.val(), 'timeout');
					processNextUpload();
					return;
				}
				jsUploadSessionId=data.sessionId;
				$form[0].setAttribute('action', origUploadUrl+jsUploadSessionId+"/");
		        // start upload
		        $form.submit();
		        // check status
		        progress();
	    	});
	}
}

var copyClip = function(copytext){
    if (window.clipboardData)
    {
    // IE
        window.clipboardData.setData("Text", copytext);
    }
    else if (window.netscape) // Netscape Base
    {
        try{
        // request privilege
        netscape.security.PrivilegeManager.enablePrivilege('UniversalXPConnect');
        } catch(e){
            alert("Permssion to copy text was denied.");
        }
        // make clipboard
        var clip = Components.classes['@mozilla.org/widget/clipboard;1'].createInstance(Components.interfaces.nsIClipboard);
        if (!clip) return;
        // maak transferable
        var trans = Components.classes['@mozilla.org/widget/transferable;1'].createInstance(Components.interfaces.nsITransferable);
        if (!trans) return;
        trans.addDataFlavor('text/unicode');
        var str = new Object();
        var len = new Object();

        var str = Components.classes["@mozilla.org/supports-string;1"].createInstance(Components.interfaces.nsISupportsString);
        str.data=copytext;

        trans.setTransferData("text/unicode",str,copytext.length*2);
        var clipid=Components.interfaces.nsIClipboard;
        if (!clip) return false;
        clip.setData(trans,null,clipid.kGlobalClipboard);
    }
    return false;
};
