var loading_msg = "Vent venligst, henter";

var uploaded = new Array();
var upload_ids = new Array();
var avg = new Array(0,0);
var name_max_length = 25;
var sim_upload = 2;
var next_step = "";
var initialized = false;

function initializeUploader(){
    
    if(initialized){
        return;
    }
    initialized = true;
      var fileQueue = [];
      var uploadCount = 0;
      var uploadBytes = 0;
      var uploadTotal = 0;
      var startOffset = 0;
      var size_small_error = false; // If size is too smalll then
      // First getting image size to mask flahs uploader on it
    // Here some how to position
    $(document).ready(function() {
        var userid = $('#userid').val();
        var userauth = $('#userauth').val();
        var album = $('#album').val();
        var backend = $('#backend').val();        
        var server_base = $('#server_base_url').val();
        
        $( '#total_progress' ).progressbar({value: 0});
        $( '#cancel_button').hide();
        $( '#start_button').hide();
      $('#uploadify').uploadify({
        'uploader'  : server_base + 'scripts/upload/uploadify.swf',
        'script'    : server_base + 'scripts/upload/uploadify.php',
    //    'cancelImg' : '/uploadify/cancel.png',
        'scriptData'     : {'auth': userauth, 'userid': userid, 'album': album, 'backend': backend},
        'folder'    : '/upload',
        'auto'      : true,
        'hideButton'     : true,
        'wmode'          : 'transparent',
//      'buttonImg'      : server + 'images/icons/del.png',
        'folder'         : 'uploads',
        'queueID'        : 'fileQueue',
        'multi'          : true,
        'simUploadLimit' : sim_upload,
        'fileExt'        : '*.jpg;*.jpeg;*.JPG;*.JPEG;*.gif;*.GIF;*.tif;*.TIF;*.png;*.PNG',
        'fileDesc'       : 'Images (jpeg, gif and tif)',
        'buttonText'     : 'Find billeder',
        'height'         : 74,
        'width'          : 170,
        'rollover'      : false,
        'onSelect': function( event, queueID, fileObj ) {  
            // fileObj.name
            // fileObj.size
            // fileObj.creationDate
            // fileObj.modificationDate
            // fileObj.type
//            hideShowRemoteIcons(true);
            $('#upload_progress').show('fast');
            $('#cancel_button').show();
            // Check for duplicates
            var id = fileObj.name + fileObj.size;
            // Clone template
            var template = $('#upload_template');
            var cancel_icon = $('#upload_template img[class=upload_template_cancel_icon]');

            $(cancel_icon).attr('onClick', "javascript: cancelUpload('" + queueID + "');");

            var object = template.clone()
               .attr('id','fileUpload'+queueID)
               .attr('title', fileObj.name );

            template.parent().append( object );

            // Init progressbar
            $('#progressbar', object).progressbar({
                value: 0
            });

            // Get filename
            var fileObjName = fileObj.name.split('.');
            fileObjName.pop();
            fileObjName = fileObjName.join('.');

            var stripped_filename = fileObjName.substr(0,name_max_length);

            if(fileObjName.length != stripped_filename.length){
                stripped_filename = stripped_filename + "...";
            }

            // Set filename

            $('#image_preview_name', object).html(stripped_filename);
            object.show();

            fileQueue.push( queueID );
            uploadBytes += fileObj.size;

            uploadTotal++;

            upload_ids[queueID] = uploadTotal;
            // Resize page
//            resizePage();
            uploaded[id] = true;

            $( '#cancel_button').show();
            $( '#back_button').hide();

            return false;

         }
         ,'onProgress': function( event, queueID, fileObj, data ) {
            // fileObj.name
            // fileObj.size
            // fileObj.creationDate
            // fileObj.modificationDate
            // fileObj.type

            // data.percentage;
            // data.bytesLoaded;
            // data.allBytesLoaded;
            // data.speed;
            var progress = Math.round(100 * data.allBytesLoaded / uploadBytes);                
            updateProgressBar(progress);

//              // To enable Cancel Uplaod button
            $( '#fileUpload' + queueID + ' #progressbar' ).progressbar( 'option', 'value', data.percentage );

            if(data.percentage == 100){
                data.percentage = "Gemmer";
            }else{
                data.percentage = data.percentage + '%';
            }

            var cur_speed = Math.round( data.speed, 1 );
            $( '#fileUpload' + queueID + ' #avg_speed' ).html( '(' + cur_speed + ' KB/s)');

            // Set/get total avarage
            avg[upload_ids[queueID]%sim_upload] = cur_speed;

            // Get total speed
            speed = avg[0] + avg[1];
            //alert("Total: " + speed + ", " + avg[0] + "+" + avg[1] + ": (" + (upload_ids[queueID]%sim_upload) + ")");

            $( '#current_speed' ).html(speed + 'KB/s');
//                $( '#current_speed' ).innerHTML = speed + 'KB/s';
            $( '#cancel_button').show();
            $( '#back_button').hide();

            return true;

         },'onComplete': function( event, queueID, fileObj, response, data ) {
            // fileObj.name
            // fileObj.size
            // fileObj.creationDate
            // fileObj.modificationDate
            // fileObj.type                
            // data.fileCount;
            // data.speed;
            $( '#fileUpload' + queueID + ' #progressbar' )
               .progressbar( 'option', 'value', 100 );
            if(response == "ERROR"){ // File Size Error
                var txt = "<span class=\"status_fail\"><div id=\"\" style=\"float: left;padding-top: 1px;\" >Too small image&nbsp;&nbsp;</div><div style=\"float: left;\"><img src='" + server + "images/icons/fail_icon.png'  /></div></span> ";
                $( '#fileUpload' + queueID + ' #status' ).innerHTML = txt;
                $( '#fileUpload' + queueID + ' img:[class^=upload_thumb]' )
                   .attr( 'src', (server_base + 'images/icons/thumb_preview.png') )
                   .attr( 'id', response );
               size_small_error = true;
            }else{
                var txt = "<div class=\"status_pass\"><div id=\"\" style=\"float: left; padding-top: 1px;\" >Billedet er nu uploaded&nbsp;&nbsp;</div><div style=\"float: left;\"><img src='" + server + "images/icons/pass_icon.png'  /></div></div> ";
                $( '#fileUpload' + queueID + ' #status' ).html(txt);
                $( '#fileUpload' + queueID + ' img:[class^=upload_thumb]' )
                   .attr( 'src', (server_base + 'downloadUserFile.php' + response) )
                   .attr( 'id', response );
            }
            $( '#fileUpload' + queueID + ' img:[class=upload_template_cancel_icon]' ).remove();
            $( '#fileUpload' + queueID + ' #avg_speed' ).html(Math.round( data.speed, 1 ) + ' KB/s');
            // Add preview of uploaded image
            $( '#fileUpload' + queueID + ' .progressbar' );
            var cur_speed = Math.round( data.speed, 1 );
            $( '#fileUpload' + queueID + ' #avg_speed' ).html( '(~' + cur_speed + ' KB/s)');    
            return false;

         }, 
         'onCancel': function( event, queueID, fileObj, errorObj ) {
                $('#fileUpload' + queueID).remove();                
                nextPage($('#next_step').val(), '');
             }, 'onClearQueue': function(event, data) {
                var next_step = $('#next_step').val() + "?step=1";
                nextPage(next_step, target);
             }, 'onError': function( event, queueID, fileObj, errorObj ) {
                alert('An error occoured uploading the file: ' + errorObj.info + '\nError code: ' + errorObj.type);
//                $('#about').show('fast');
                $('.remote_icon').show('fast');
             }, 
        'onAllComplete': function( event, data ) {
//                $( '#current_speed' ).html(Math.round(data.speed, 1) + 'KB/s'); 
                $( '#current_speed' ).innerHTML = Math.round(data.speed, 1) + 'KB/s';
                $( '#upload_progress' ).fadeOut("100", function (){
                    $( '#cancel_button').hide();
                    if(size_small_error){
                        alert('billederne er desværre for små');
                        window.lcoation = $('#server_base_url').val();
                        return;
                    }else{
                        nextPage($('#next_step').val(), '');
                        return;
                    }

                });
             }         
      });
        $('body img').imgpreload
        ({
                all: function()
                {
                    AdjustUploaderFlashPosition();
                }
        });

        // Bind Buttons Behavious
        bindButtonEvents();
        // Bind Upload images tags
    });    
}    
    
function bindButtonEvents(){

    // bind images upload template icons
    
    $('img#upload_template_cancel_icon').mouseover( function(){
         swapimage($(this), $('input#input_hover').val() );
    });
    $('img#upload_template_cancel_icon').mouseout( function(){
         swapimage($(this), $('input#input_out').val() );
    });
}
 /**
 *AdjustUploaderFlashPosition
 * adjust flahs uploader position right on upload_button
 */
function AdjustUploaderFlashPosition(){
    // getting find billeder button positition
    var left = $('img#upload_button').position().left;
    var top = $('img#upload_button').position().top;
    if( $.browser.msie ){
    }
    // PLace flash Uplaoder on top of it
    $('#uploader_container').css('float', 'left' );
    $('#uploader_container').css('left', 'left' );
    $('#uploader_container').css('top', 'top');
//    $('#uploadify').css('left', '0px');
    $('#uploader_container').css('position', 'absolute' );  
    $('#uploadifyUploader:object').css('left', '0px');
}
function hoverIcon(){
    var new_icon = server + 'images/photo/upload/hent_computer.png';
    var new_icon = $('input[type=hidden]#upload_button_hover').val();
    $('#upload_button').attr('src', new_icon);
}

function restoreIcon(){
    var new_icon = server + 'images/photo/upload/hent_computer.png';
    var new_icon = $('input[type=hidden]#upload_button_out').val();
    $('#upload_button').attr('src', new_icon);
}

function showNextButton(){
    $('#next_button').fadeIn("1000");
}

function updateProgressBar(progress){
    
    if(progress == NaN){
        progress = 100;
    }
    $( '#total_progress' ).progressbar( 'option', 'value', progress);

    // Change progress bar color
    if(progress>=50){
        $( '#total_progress_nb' ).css('color', '#ffffff');
    }
    $( '#total_progress_nb' ).html(progress + '%');
//    $( '#total_progress_nb' ).innerHTML = progress + '%';
}
/**
 * This function is called from to stop and cancel uploading
 * 
 */
function cancelUploading(){
//    $('#uploadify').uploadifyCancel();
    disable();
    $('#uploadify').uploadifyClearQueue();
    enable();    
//    $('.upload_template:visible').remove();
    // Now Remove all DOM od div with class name uplaod_temp except of one invisible
//    $('div .upload_template[id^=fileUpload]').remove();
//    //$("#upload_progress").remove();
//    $('#next_button').hide();
//    $('#upload_progress').fadeOut("100");
//    $('#cancel_button').hide();

}
/**
 *
 **/
function startUploading(link){
     $('#uploadify').uploadifyUpload();
     next_step=link;
}
/**
 * THis function is used to simply delete single image in the queue ready to upload
 */
function cancelUpload(queID){
//    alert('Going to hide');
//     $('#fileUpload' + queID).hide();
     $('#uploadify').uploadifyCancel(queID);
     $('#fileUpload' + queID ).remove();
//    $('#about').show('fast');
//                        $('#picasa_container').show('fast');
    $('.remote_icon').show('fast');
//     $('.upload_template').remove();
}
function nextPage(link, target){    
//    startUploading();
    disable(loading_msg);    
    //alert($('#next_page').val() + link);
    if(target == "_top"){
        top.window.location = link;
    }else{
        window.location = link;
    }
}
initializeUploader();

function hideShowRemoteIcons(hide){
    if(hide){
        $('#about').hide('fast');
        $('#picasa_container').hide('fast');
        $('#twitter_container').hide('fast');
        $('#flickr_container').hide('fast');
        $('.remote_icon').hide('fast');
        $('.info_icon').hide('fast');
    }else{
        $('.remote_icon').show('fast');
        $('.info_icon').show('fast');

        $('#about').show('fast');
//        $('#picasa_container').('fast');
//        $('#twitter_container').hide('fast');
//        $('#flickr_container').hide('fast');

    }
}

function loginDifferentUser(data_source){
    var data = "action=loginDifferentUser"  + "&" +
               "data_source=" + data_source
               ;
    var url = server + "scripts/php/photorder_responder.php";

    $.ajax({
        type: "POST",
        url: url,
        data: data,
        success: function(data){
            $('#' + data_source + '_container').html(data);
        }
    });

}

/**
 */
function disableEnterKey(e, funcCall)
{
     var key;
     if(window.event)
          key = window.event.keyCode; //IE
     else
          key = e.which; //firefox
     if(key == 13){
         eval(funcCall + "();");
        return false;
    }else
         return true;
}

function bubbleHelp(help_image_path){
    // first tryo to hide all div except of container
    switchContainer(1);
    $('table#about img#help_image').attr('src', help_image_path);
}
/**
 * @param1 id 1 for computer
 * 2 for twitter
 * 3 for picasa
 * 4 for flickr
 */
function switchContainer(id){
    var speed='fast';
    switch(id){
        case 1:
            $('#computer_container').show(speed);
            $('#twitter_container').hide(speed);
            $('#picasa_container').hide(speed);
            $('#flickr_container').hide(speed);
            break;
        case 2:
            $('#computer_container').hide(speed);
            $('#twitter_container').show(speed);
            $('#picasa_container').hide(speed);
            $('#flickr_container').hide(speed);
            break;
        case 3:
            $('#computer_container').hide(speed);
            $('#twitter_container').hide(speed);
            $('#picasa_container').show(speed);
            $('#flickr_container').hide(speed);
            break;
        case 4:
            $('#computer_container').hide(speed);
            $('#twitter_container').hide(speed);
            $('#picasa_container').hide(speed);
            $('#flickr_container').show(speed);
            break;
    }
}
