var siteBackDelay = new Array(), 
    current = 0, 
    total = 0, 
    screenWidth, 
    screenHeight, 
    screenRation, 
    globalStep = 0,
    swfUploader = null,
    swfLeft = 0,
    swfTop = 0;

$(document).ready(function(){
    
    PreventOnClose();
    
    if(dhash.length == 0) LoadUploader();
    
    LoadBackgrounds();
    ChangeBackgrounds();
    LoadUploadSteps();
    
    if(dhash.length == 0)
    {
        SetupSteps();
        PrepareEmailsPasswords();
    }
    
    $('#uploadfile').click(function(){
        var ispass = $('.passwordarea');
        if(ispass.hasClass('pass')==true)
        {
            ispass.slideDown(250);
            var p = $('.passwordinput').val();
            if(p.length > 0)
            {
                SendGetAjax('template/ajax.php?p='+encodeURIComponent(p)+'&f='+dfile,function(response){
                    if(parseInt(response)==0)
                    {
                        $('.passwordinput').val('');
                        $('.passwordinput').animate({backgroundColor:"#F00"},500,function(){
                            setTimeout(function(){
                                $('.passwordinput').animate({backgroundColor:"#FFF"},500);
                            },2000);
                        })
                    }
                    else
                    {
                        setCookie("downloadhash", response, "Mon, 01-Jan-2050 00:00:00 GMT", "/");
                        window.location = '/?f='+dfile;
                    }
                });
            }
        }
        else
        {
            setCookie("downloadhash", dhash, "Mon, 01-Jan-2050 00:00:00 GMT", "/");
            window.location.reload(true);
        }
    });
});

function setCookie(name, value, expires, path, domain, secure) {
    document.cookie = name + "=" + escape(value) +
    ((expires) ? "; expires=" + expires : "") +
    ((path) ? "; path=" + path : "") +
    ((domain) ? "; domain=" + domain : "") +
    ((secure) ? "; secure" : "");
}

function PreventOnClose()
{
    if(dhash.length == 0) 
    {
        $(window).blur(function() {
            SendGetAjax('template/close.php?a=blur&id='+global_key,function(r){}); 
        });
        $(window).focus(function() {
            SendGetAjax('template/close.php?a=focus&id='+global_key,function(r){}); 
        });
    }
}

function LoadBackgrounds()
{
    screenWidth = $(document).width();
    screenHeight = $(document).height();
    screenRation = screenWidth / screenHeight;
    
    $('.background-holder').find('input').each(function(){
        
        var file = $(this).attr('file');
        var title = $(this).attr('title');
        var url = $(this).attr('url');
        var size = $(this).attr('isize').split('x');
        var bWidth  = parseInt(size[0]);
        var bHeight = parseInt(size[1]);
        var bRatio  = bWidth / bHeight;

        var html = $('.background-holder').html();
        $('.background-holder').html(html + '<img src="/template/images/back/' + file + '" alt="' + title + '" id="back' + total + '" onclick="window.location=\'' + url + '\'" />' + "\n");
        $(this).remove();
        
        if(bRatio < screenRation)
        {
            var newBHeight = bHeight + (screenWidth - bWidth) / bRatio;
            var newBTop = (newBHeight - screenHeight) / 2;
            $('#back'+total).css({ 'width' : screenWidth + 'px', 'height' : newBHeight + 'px', 'top' : '-' + newBTop + 'px', 'z-index': 100 - total});
        }
        else
        {
            var newBWidth = bWidth + (screenHeight - bHeight) / bRatio;
            var newBLeft = (newBWidth - screenWidth) / 2;
            $('#back'+total).css({ 'width' : newBWidth + 'px', 'height' : screenHeight + 'px', 'left' : '-' + newBLeft + 'px', 'z-index': 100 - total});
        }
        
        siteBackDelay[total] = parseInt($(this).attr('delay'));
        total++;
        
    });
    total--; 
    
    swfLeft = screenWidth / 2 - 133;
    swfTop = screenHeight / 2 - 140;
    $('#SWFUpload_0').css({'left':swfLeft+'px','top':swfTop+'px'});
    $('body').css({'display':'block'});
}

function ChangeBackgrounds()
{
    setTimeout(function(){

        $('#back'+current).fadeOut(2000,function(){
            
            $('.background-holder img').each(function(){
                $(this).css({'z-index':(parseInt($(this).css('z-index'))+1)});  
            });
            $('#back'+current).css({'z-index':'0'});
            $('#back'+current).fadeIn(100,function(){
                current++;
                if(current > total) current = 0;
                ChangeBackgrounds();
            });
        });
            
    },parseInt(siteBackDelay[current]));
}

function LoadUploadSteps()
{
    $('.app-holder').draggable({ 
        snap : 'body', 
        containment : 'parent',
        start : function(){
            $('.popupLeft').hide();   
            $('.popupRight').hide();
            $('.popupTop').hide();
        },
        drag : function(event, ui){
            var y = ui.position.top + 70;
            var x = ui.position.left + 5;
            swfTop = y;
            y+=scrollHeight;
            $('#SWFUpload_0').css({'top':y+'px','left':x+'px'});
        }
    });
    var appTop = screenHeight / 2 - parseInt($('.app-holder').height()) / 2 - 8;
    var appLeft = screenWidth / 2 - parseInt($('.app-holder').width()) / 2 - 8;
    $('.app-holder').css({'top' : appTop + 'px','left' : appLeft + 'px'});        
}

function SetupSteps()
{
    $('.major').click(function(){
        if(globalStep==0)
        {
            $('.step-welcome').fadeOut(500,function(){
                swfUploader.setButtonDimensions(220,23);
                $('.step-files').fadeIn(500,function(){
                    $('.scroll-pane').jScrollPane();
                });
            });
        }
        if(globalStep==1)
        {
            var res = TryUpload();
            if(res)
            {
                swfUploader.setButtonDimensions(1,1);
                $('.step-files').fadeOut(500,function(){
                    $('.step-loading').fadeIn(500,function(){
                        setTimeout(function(){
                            swfUploader.startUpload();
                        },1000);
                    });
                });
            }
            else globalStep = 0;
        }
        if(globalStep==2)
        {
            swfUploader.destroy();
            window.location = "/";
        }
        globalStep++;
        if(globalStep > 2)globalStep = 1;
    });    
}

function LoadUploader()
{
    var d = new Date();     
    setCookie("USERKEY", global_key, "Mon, 01-Jan-2050 00:00:00 GMT", "/");
    swfUploader = new SWFUpload(
    {
        // Backend Settings
        upload_url: "/template/upload.php?userkey="+global_key,
        file_post_name : "Filedata",
        
        // File Upload Settings
        file_size_limit : global_maxsize,
        file_types : "*.*",
        file_types_description : "All Files",
        file_upload_limit : '0',
        file_queue_limit : global_maxfiles,

        // Event Handler Settings (all my handlers are in the Handler.js file)  
        file_queued_handler : fileQueued,
        file_queue_error_handler : fileQueueError,
        upload_start_handler : uploadStart,
        upload_progress_handler : uploadProgress,
        upload_error_handler : uploadError,
        upload_success_handler : uploadSuccess,
        upload_complete_handler : uploadComplete,
        file_dialog_complete_handler  : fileDialogComplete,
						
        // Button Settings
        button_image_url:'/template/images/site/buttonUpload.png',
        prevent_swf_caching:true,
        assume_success_timeout:0,
        button_placeholder_id : "uploader",
        button_width: 1,
        button_text : '<p align="right" class="righttext">(Free: '+(parseInt(global_maxsize) / 1024)+' Mb)</p>',
        button_text_style:'.righttext{color:#aaaaaa; font-family:Tahoma; font-size:10pt;}',
        button_text_top_padding: 3,
        button_text_left_padding: -7,
        button_height: 1,
        button_cursor : SWFUpload.CURSOR.HAND,
		
		// Flash Settings
		flash_url : "/template/libs/swfupload/swfupload.swf?some="+d.getTime(),
		custom_settings : 
        {
		    progressTarget : "uploaderFiles",
			cancelButtonId : "cancel",
		},
        
		// Debug Settings
		debug: false
    });
}

function PrepareEmailsPasswords()
{
    $('.receiveEmail').focus(function(){
        $(this).addClass('active');
        var val = $(this).val();
        if(val=='E-mail получателя файлов')$(this).val('');
    });
    $('.receiveEmail').blur(function(){
        $(this).removeClass('active');
        var val = $(this).val();
        if(val.length==0)$(this).val('E-mail получателя файлов');
    });

    $('.authorEmail').focus(function(){
        $(this).addClass('active');
        var val = $(this).val();
        if(val=='Ваш E-mail')$(this).val('');
    });
    $('.authorEmail').blur(function(){
        $(this).removeClass('active');
        var val = $(this).val();
        if(val.length==0)$(this).val('Ваш E-mail');
    });

    $('.fileComments').focus(function(){
        $(this).addClass('active');
        var val = $(this).val();
        if(val=='Комментарий (не обязательно)')$(this).val('');
    });
    $('.fileComments').blur(function(){
        $(this).removeClass('active');
        var val = $(this).val();
        if(val.length==0)$(this).val('Комментарий (не обязательно)');
    });
    
    $('.passw1').focus(function(){
        $(this).addClass('active');
        $(this).removeClass('hasval');
    });
    $('.passw1').blur(function(){
        $(this).removeClass('active');
        var val = $(this).val();
        if(val.length > 0) $(this).addClass('hasval');
        else $(this).removeClass('hasval');
    });
    
    $('.passw2').focus(function(){
        $(this).addClass('active');
        $(this).removeClass('hasval');
    });
    $('.passw2').blur(function(){
        $(this).removeClass('active');
        var val = $(this).val();
        if(val.length > 0) $(this).addClass('hasval');
        else $(this).removeClass('hasval');
    });
    
    $('.passNeed').change(function(){
        if($(this).attr('checked')==true)
            $('.passwNeedHolder').animate({height:55},500);
        else $('.passwNeedHolder').animate({height:19},500);
    });
}

function TryUpload()
{
    var totalFilesSize = parseInt($('#totalfilesize').val());
    var receiverEmail = $('.receiveEmail').val();
    var authorEmail = $('.authorEmail').val();
    var passNeed = $('.passNeed').attr('checked');
    var passw1 = $('.passw1').val();
    var passw2 = $('.passw2').val();
    
    if(totalFilesSize == 0)
    {
        var w = $('.uploaderFilesHolder').width();
        var h = parseInt($('.uploaderFilesHolder').css('height'));
        var o = $('.uploaderFilesHolder').offset();
        var x = o.left;
        var y = o.top;
        $('#filesPopup').stop();
        $('#filesPopup').css({ top : (y + 5)+'px', left : (x - (w / 3 * 2) - 5)+'px' });
        $('#filesPopup').fadeIn(500,function(){
            setTimeout(function(){
                $('#filesPopup').fadeOut(500);
            },3000);
        });                
        return false;
    }
    
    if(receiverEmail.indexOf('@') < 0 || receiverEmail == '' || receiverEmail == 'E-mail получателя файлов')
    {
        var w = $('.receiveEmail').width();
        var h = parseInt($('.receiveEmail').css('height'));
        var o = $('.receiveEmail').offset();
        var x = o.left;
        var y = o.top;
        $('#receiverPopup').stop();
        $('#receiverPopup').css({ top : (y - 46)+'px', left : (x - (w / 3 * 2) - 10)+'px' });
        $('#receiverPopup').fadeIn(500,function(){
            setTimeout(function(){
                $('#receiverPopup').fadeOut(500);
            },3000);
        });                
        return false;
    }
    
    if(authorEmail.indexOf('@') < 0 || authorEmail == '' || authorEmail == 'Ваш E-mail')
    {
        var w = $('.authorEmail').width();
        var h = parseInt($('.authorEmail').css('height'));
        var o = $('.authorEmail').offset();
        var x = o.left;
        var y = o.top;
        $('#authorPopup').stop();
        $('#authorPopup').css({ top : (y - 46)+'px', left : (x + w + 20)+'px' });
        $('#authorPopup').fadeIn(500,function(){
            setTimeout(function(){
                $('#authorPopup').fadeOut(500);
            },3000);
        });                
        return false;
    }
    
    if(passNeed==true)
    {
        if(passw1.length == 0)
        {
            var w = $('.passw1').width();
            var h = parseInt($('.passw1').css('height'));
            var o = $('.passw1').offset();
            var x = o.left;
            var y = o.top;
            $('#emptyPassPopup').stop();
            $('#emptyPassPopup').css({ top : (y - 46)+'px', left : (x - w - 60)+'px' });
            $('#emptyPassPopup').fadeIn(500,function(){
                setTimeout(function(){
                    $('#emptyPassPopup').fadeOut(500);
                },3000);
            });                
            return false;
        }

        if(passw2.length == 0)
        {
            var w = $('.passw2').width();
            var h = parseInt($('.passw2').css('height'));
            var o = $('.passw2').offset();
            var x = o.left;
            var y = o.top;
            $('#emptyConfirmPopup').stop();
            $('#emptyConfirmPopup').css({ top : (y - 46)+'px', left : (x + w + 20)+'px' });
            $('#emptyConfirmPopup').fadeIn(500,function(){
                setTimeout(function(){
                    $('#emptyConfirmPopup').fadeOut(500);
                },3000);
            });                
            return false;
        }
        
        if(passw1 !== passw2)
        {
            var w = $('.passw1').width();
            var h = parseInt($('.passw1').css('height'));
            var o = $('.passw1').offset();
            var x = o.left;
            var y = o.top;
            $('#notSamePassPopup').stop();
            $('#notSamePassPopup').css({ top : (y - 46)+'px', left : (x - w - 60)+'px' });
            $('#notSamePassPopup').fadeIn(500,function(){
                setTimeout(function(){
                    $('#notSamePassPopup').fadeOut(500);
                },3000);
            });                
            return false;
        }

    }
    
    return true;
}

function CreateRequest()
{
    var Request = false;
    if (window.XMLHttpRequest) { Request = new XMLHttpRequest(); }
    else if (window.ActiveXObject)
    {
        try { Request = new ActiveXObject("Microsoft.XMLHTTP"); }
        catch (CatchException) { Request = new ActiveXObject("Msxml2.XMLHTTP"); }
    }
    if (!Request) { alert("Невозможно создать XMLHttpRequest"); }
    return Request;
}

function SendGetAjax(url,func)
{
    var xmlHttp = CreateRequest();
  	xmlHttp.open("GET", url, true);
    xmlHttp.onreadystatechange = function()
    {
        if (xmlHttp.readyState == 4)
        {
            var response = xmlHttp.responseText;
            func(response);
        }
    };
    xmlHttp.send(null);
}
