// Place your application-specific JavaScript functions and classes here
// This file is automatically included by javascript_include_tag :defaults
function removeFocus() {
    if(document.getElementsByTagName) {
//        var links = Element.select(document, 'a');
        var links = $$('div#rating_placeholder a');
        links.each(function(a) {
            a.onmousedown = (function() {
                this.blur();                 // most browsers
                this.hideFocus = true;       // internet explorer
                this.style.outline = 'none'; // mozilla
            });
            a.onmouseout = a.onmouseup = (function() {
                this.blur();                 // most browsers
                this.hideFocus = false;      // internet explorer
                this.style.outline = null;   // mozilla
            });
        });
    }
}

Ajax.Responders.register({
    onCreate: function(request) {
        if (!request.url.match(/progress/)) {
            //$('splash').show();
            document.body.style.cursor = "progress";
        }
    },
    onComplete: function(request) {
        // Assuming the ga.js code was loaded first
        if (!request.url.match(/\/progress|\/videos|\/session/)) {
            pageTracker._trackPageview(request.url);
        }
        removeFocus();
        document.body.style.cursor = "default";
        //$('splash').hide();
    }
});

function getSiteLocation() {
    /* the app is running on an iframe? */
    if (parent == self) {
        return window.location.href;
    } else {
        try {
            for (var i = 0; i < parent.frames.length; i++) {
                try {
                    if (parent.frames[i] == self) {
                        if (parent.frames[i].name) {
                            return parent.frames[i].name.split('_')[1];
                        }
                    }
                } catch (e) {}
            }
        } catch (e2) {}
        var search = location.search;
        if (search) {
            var parameterName = "referral_url=";
            var begin = search.indexOf(parameterName);
            var end;
            if (begin != -1) {
                begin += parameterName.length;
                end = search.indexOf( "&", begin );
                if ( end == -1 ) {
                    end = search.length;
                }
                return unescape(search.substring(begin, end));
            }
        }
    }
}

function getSiteHost() {
    var parentLocation = getSiteLocation();
    return parentLocation.split('?')[0];
}

function getSiteParameters() {
    var parentLocation = getSiteLocation();
    locationParts = parentLocation.split('?');
    if (locationParts.length > 1) {
        return "?" + locationParts[1];
    } else {
        return "";
    }
}

function setElementLocation(elem) {
    $(elem).value = getSiteLocation();
}

Event.observe(window, 'load', function() {
    removeFocus();
    if ($('search')) {
        if (navigator.appName.match(/Internet Explorer/)) {
            Event.observe('search', 'keydown', function(event) {
                if (event.keyCode == 13) {
                    $('search_form').submit();
                }
                /*Event.stop(event);*/
            });
        }
    }
});



/*
Firefox doesn't work with keydown event on elements,
that's the way it works
document.observe('keydown', function(event) {
    if (event.target.id == 'search' && event.keyCode == 13) {
        $('search_form').submit();
    }
});
*/


// Upload with progress tracker
function doUpload(uuid) {
    $('upload_link').hide();
    $('non-completed').hide();
    $('bar-message').update($$('div.highslide-body input#video_video').first().value);
    $('preload').show();
    //update the progress bar
    uploadProgressTracker = new PeriodicalExecuter(
        function(){
            if(Ajax.activeRequestCount === 0){
                new Ajax.Request("progress",{
                    method: 'get',
                    parameters: 'X-Progress-ID=' + uuid,
                    onSuccess: function(xhr){
                        var upload = xhr.responseText.evalJSON();
                        if(upload.state == 'uploading'){
                            upload.percent = Math.floor((upload.received / upload.size) * 100);
                            var bar = $('bar');
                            bar.setStyle({width: upload.percent + "%"});
                            bar.update("<span class=''>" + upload.percent + "%</span>");
                        } else if(upload.state == 'done') {
                            //stop the periodical executer and display message
                            uploadProgressTracker.stop();
                        } else if(upload.state == 'error') {
                            //stop the periodical executer and display message
                            uploadProgressTracker.stop();
                            $('preload').hide();
                            nonCompletedText = $('non-completed-text');
                            nonCompletedText.update("<br />Fehler! Das Hochladen wurde unterbrochen. Bitte klicken Sie <a href='#' onclick=\"$('non-completed').hide();$('upload_link').show();\">HIER</a>, um es erneut zu versuchen.<br />");
                                $('non-completed').show();
                        }
                    }
                });
            }
        }, 4);
    $$('div.highslide-body #new_video').first().submit();
    hs.close();
}

function validateUpload(uuid) {
    new Ajax.Request(relative_root + "videos/validate", {
        method: 'get',
        parameters: $$('div.highslide-body #new_video').first().serialize(),
        onSuccess: function(transport){
            if (transport.responseText.length > 1) {
                return eval((transport.responseText || '').unfilterJSON());
            } else {
                return doUpload(uuid);
            }
        }
    });
    return false;
}

function stopProgressTracker() {
    if (uploadProgressTracker) {
        uploadProgressTracker.stop();
    }
}
