/// <reference path="jquery-1.4.1-vsdoc.js">
// steidle new media 17.08.2011 ls

var type;
var counter = new Image();
var x = new Image();
var autoplay = true;
$(document).ready(function () {

    document.onclick = function (event) {
        var target = window.event ? window.event.srcElement : event.target;
        if (target.className == "padding" || target.className == "button" || target.parentNode.className == "button")
            myget$('movie').stopVideo();
    }

    blockUI();

    try {
        if (charts != undefined && charts.length > index + 1)
            x.src = charts[index + 1].image;
    }
    catch (e) { }
    if (type != undefined && type == "audio") {

        var solutions = $.browser.msie && $.browser.version == "9.0" ? "flash" : "html, flash";

        $("#audioplayer").jPlayer({
            ready: function () {
                $(this).jPlayer("setMedia", {
                    mp3: audioFile
                }).jPlayer("play");

                debug("load " + audiofile);

                if (index > 0)
                    sJumpTo = index;
            },
            solution: solutions, // Flash with an HTML5 fallback.
            swfPath: "javascripts/",
            preload: "auto",
            errorAlerts: true

        });



        try {
            completetime = getAudioLength(charts.length);
        }
        catch (e) { completetime = 500; }

        bind();
    }

    if (type != undefined && type == "multipleaudio") {

        // Problems with ie9 and some mp3
        var solutions = $.browser.msie && $.browser.version == "9.0" ? "flash" : "html, flash";

        $("#audioplayer").jPlayer({
            ready: function () {
                if (autoplay) {
                    $(this).jPlayer("setMedia", {
                        mp3: charts[index].fileaudio
                    }).jPlayer("play");

                    if (index > 0)
                        sJumpTo = index;
                }
            },

            solution: solutions, // Flash with an HTML5 fallback.
            swfPath: "javascripts/",
            preload: "auto",
            errorAlerts: false

        });

        completetime = getAudioLength(charts.length);
        addtime = getAudioLength(index);

        bind();
    }


    $("#thumbslink").click(function (event) {
        pause();
        var oldheight = $("#chartdiv").height();
        $("#chartdiv").css("overflow", "hidden").height(1);
        $("#navigation").hide();
        $('#mthumbs').load('index.php?menu=thumbs&id=' + id + ' #contentwrapper', function () {
            $("#mthumbs").show();
            $("#mthumbs .thumbnail").click(function (event) {
                event.preventDefault();
                $("#chartdiv").height(oldheight);
                $("#navigation").show();
                $("#mthumbs").hide();
                index = parseInt($(this).attr("index"));
                show(parseInt($(this).attr("index")));

                play();
                bind();
            });
        });
        event.preventDefault();
    });

    try {
        addText();
    } catch (a) { }
});

var addtime = 0;
var completetime = 0;

function getAudioLength(until) {
    var result = 0;
    for (var i = 0; i < until; i++)
        result += charts[i].timecode;
    
    //return charts[until].timecode;
    return result;
}

function bind() {
    $("#audioplayer").bind($.jPlayer.event.timeupdate, function(event) { // Add a listener to report the time play began
        duration = event.jPlayer.status.duration;
        if (sJumpTo != -1) {
            show(sJumpTo);
            sJumpTo = -1;
        }


        if (type != "multipleaudio")
            updateTime(event.jPlayer.status.currentTime);

        var time = $.jPlayer.convertTime(event.jPlayer.status.currentTime);
        var totaltime = $.jPlayer.convertTime(duration);
        //if (completetime > duration);
        //    totaltime = $.jPlayer.convertTime(completetime);

        if (type == "multipleaudio") {
            time = $.jPlayer.convertTime(event.jPlayer.status.currentTime + addtime);
            totaltime = $.jPlayer.convertTime(completetime);
        }

        $("#audiotimecode").text("Time: " + time + " / " + totaltime);

    });

    // mp3 fertig
    $("#audioplayer").bind($.jPlayer.event.ended, function(event) {

        if ((index + 1) < total) {
            next();
        }
        else {
            $("#audioplayer").jPlayer("stop");
            totaltime = $.jPlayer.convertTime(completetime);
            $("#audiotimecode").text("Time: " + totaltime + " / " + totaltime);
        }

    });
}

var sJumpTo = -1;

function debug($obj) {
    if (window.console && window.console.log)
        window.console.log($obj);
};

var duration = 10;

// Show chart
function displayImage(index) {

    if (charts == undefined || charts.lenght == 0)
        return;

    if (charts[index].image.indexOf(".swf") > -1) {
        $("#chartcontainer").html("<object classid=\"clsid:D27CDB6E-AE6D-11cf-96B8-444553540000\"" +
				" codebase=\"http://download.macromedia.com/pub/shockwave/cabs/flash/swflash.cab#version=5,0,0,0\" width=\"530\" height=\"398\" >\n" + 
				" <param name=\"movie\" value=\""+ charts[index].image +"\">\n" +
				" <param name=\"quality\" value=\"high\">\n" +
				" <param name=\"PLAY\" value=\"false\">\n" + 
				" <param name=\"LOOP\" value=\"false\">\n" +
				" <param name=\"BGCOLOR\" value=\"#000088\">\n" +
				"<embed src=\"" + charts[index].image + "\" width=\"530\" height=\"398\" hspace=\"5\" loop=\"false\" quality=high pluginspage=\"http://www.macromedia.com/shockwave/download/index.cgi?P1_Prod_Version=ShockwaveFlash\" type=\"application/x-shockwave-flash\" play=\"false\">\n " +
				"</embed>\n </object>");

    }
    else {
        if (charts[index].download) {
            $("#chartcontainer").html("<a target=\"_blank\" href=\"" + charts[index].download + "\"><div id=\"divchart\" style=\"background-position:center center; background-image:url('" + charts[index].image + "');width:530px;height:398px;\"><img alt=\"\" id=\"imgchart\" src=\"images/transparent.gif\" border=\"0\" width=530 height=398 /></div></a>");
        }
        else {
            $("#chartcontainer").html("<div id=\"divchart\" style=\"background-position:center center; background-image:url('" + charts[index].image + "');width:530px;height:398px;\"><img id=\"imgchart\" alt=\"\" src=\"images/transparent.gif\" border=\"0\" width=530 height=398 /></div>");            
        }
    }
    addText();
    counter.src = "index.php?id=" + id + "&action=count&chart=" + index;

//    $("#imgchart").onmousedown(function() {
//        checkIt() 
//        }); 

}

// Show chart text
function addText() {

    showChartInfo();
    
    if (charts[index].text) {
        debug("text:" + charts[index].text + " " + $("#chartcontainer>#divchart").html());
        $("#chartcontainer>#divchart").hover(function() {        
        
            var text = charts[index].text;
            var posi = $(this).position();
            var top = posi.top + 300; //top position
            var left = posi.left - 50; //left position
            var wid = $(this).width(); //element width
            $(this).parent().append('<div class="poptext">' + unescape(text.replace('|', '')) + '</div>');


            //some css styling
            $('.poptext').css({ 'left': (left + wid) + 'px',
                'top': (top - $('.poptext').height()) + 'px',
                'background': 'white',
                'text-align': 'left',
                'border': '1px solid gray',
                'display': 'none',
                'position': 'absolute',
                'z-index': '5000',
                'padding': '5px',
                'font-size': '12px',
                '-moz-box-shadow': '2px 10px 10px #000',
                '-webkit-box-shadow': '2px 10px 10px #000',
                'box-shadow': '2px 2px 10px #000'
            });

            //show tooltip, slowly
            $('.poptext').fadeIn('slow');

        },
        function() {
            var title = $(this).parent().find('.poptext').html(); //restore title text from tooltip	        
            $(this).parent().find('.poptext').fadeOut('slow'); //hide tooltip
            $(this).parent().find('.poptext').remove(); //remove element
        }
        );
    }
}


// Display time
function updateTime(time) {

    if (charts == undefined || charts.lenght == 0)
        return;


    var e = -1, t = 0, ii = 0;

    for (ii = 0; ii < total; ii++) {
        timecode = charts[ii].timecode;
        if (parseInt(timecode) < parseInt(time) && startindex < ii) {
            e = ii; // chartindex
            index = ii;
            t = timecode;
            startindex = 0;
        }
    }
    
    //debug("index:" + index + " last:" + lastindex + " | to play:" + (e/2) + " || wait:" + wait + " " + (charts.length/2) + " timecode:" + timecode + " time:" + time + "\n");			
    if (e != -1 && e < charts.length && servername + charts[e] != myget$("divchart").style.backgroundImage) {

        if (lastindex != index) {
            if (!wait) {
                displayImage(e);
                // preload new        
                if (charts[e + 1])
                    x.src = charts[e + 1].image;

                
            }
            wait = false;
        }
        lastindex = index;
    }

}

function myget$(id) { return document.getElementById(id); }

function jumpto(url) {
    stop();
    document.location.href = url;
}

function stop() {
    if (myget$('movie'))
        myget$('movie').stopVideo();
    else {
        show(0);
        $("#audioplayer").jPlayer("stop");
       totaltime = $.jPlayer.convertTime(completetime);
        $("#audiotimecode").text("Time: 00:00 / " + totaltime);
    }
}
function play() {
    if (myget$('movie'))
        myget$('movie').playVideo();
    else
        $("#audioplayer").jPlayer("play");
}
function pause() {
    if (myget$('movie'))
        myget$('movie').pauseVideo();
    else
        $("#audioplayer").jPlayer("pause");
}

function previous() {
    if (index > 0) {
        jump = -1;
        show(--index);
    }
}

function next() {
    //debug("next1 " + index + " total:" + total + " " + ((index + 1) < total));
    if ((index + 1) < total) {
        jump = 1;
        debug("next2 " + index + " total:" + total);
        show(++index);
    }
}

function showChartInfo() {
    $("#chartsinfo").html("Slides: " + (parseInt(index) + 1) + " / " + charts.length);
}

function show(i) {

    if (charts == undefined || charts.lenght == 0)
        return;

    
    wait = true;


    index = i; lastindex = i;
    jumpindex = i;
    
    displayImage(i);

    timecode = charts[i].timecode;

    showChartInfo();

    if (myget$('movie')) {
        myget$('movie').gotoTimeCode(timecode);
    }
    else if (type == "audio") {
        percent = 100 / duration * (timecode / 1);
        $("#audioplayer").jPlayer("playHead", percent);
    }
    else if (type == "multipleaudio") {
        $("#audioplayer").jPlayer("setMedia", { mp3: charts[index].fileaudio }).jPlayer("play");
        addtime = getAudioLength(index);
        //alert(addtime);
        debug("mp3:" + charts[index].fileaudio);
    }

    debug("goto timecode:" + timecode + " d:" + duration + " index:" + jumpindex);
}
function Mod(X, Y) { return X - Math.floor(X / Y) * Y }
function Div(X, Y) { return Math.floor(X / Y) }


function blockUI() {
    if ($("#confirm").length > 0) {
        //$.cookie('validated', 'false');

        if ($.cookie('validated') != "true") {
            autoplay = false;

            $("#confirmyes").click(function (e) {
                e.preventDefault();
                if (!$("#confirmaccept").is(':checked')) {
                    $("#confirmerror").show();
                    //alert("hwer");
                }
                else {
                    if ($("#confirmemail").val() != "") {

                        $.ajax({
                            url: 'index.php?action=register&email=' + $("#confirmemail").val() + "&country=" + $("#confirmcountry").val(),
                            cache: false,
                            complete: function (data) {
                                // unblock when remote call returns
                                $.unblockUI();
                                $.cookie('validated', 'true');
                                show(index);
                            }
                        });

                    }
                    else {
                        $.unblockUI();
                        $.cookie('validated', 'true');
                        show(index);
                    }
                }
            });

            $("#confirmno").click(function (e) {
                e.preventDefault();
                document.location.href = '/';
            });

            $.blockUI({
                message: $('#confirm'),
                css: { width: '440px', height: '310px', top: '220px', backgroundColor: '#fff', cursor: ''
                }
            });

        }
    }
}


/**
* Cookie plugin
*
* Copyright (c) 2006 Klaus Hartl (stilbuero.de)
* Dual licensed under the MIT and GPL licenses:
* http://www.opensource.org/licenses/mit-license.php
* http://www.gnu.org/licenses/gpl.html
*
*/

/**
* Create a cookie with the given name and value and other optional parameters.
*
* @example $.cookie('the_cookie', 'the_value');
* @desc Set the value of a cookie.
* @example $.cookie('the_cookie', 'the_value', { expires: 7, path: '/', domain: 'jquery.com', secure: true });
* @desc Create a cookie with all available options.
* @example $.cookie('the_cookie', 'the_value');
* @desc Create a session cookie.
* @example $.cookie('the_cookie', null);
* @desc Delete a cookie by passing null as value. Keep in mind that you have to use the same path and domain
*       used when the cookie was set.
*
* @param String name The name of the cookie.
* @param String value The value of the cookie.
* @param Object options An object literal containing key/value pairs to provide optional cookie attributes.
* @option Number|Date expires Either an integer specifying the expiration date from now on in days or a Date object.
*                             If a negative value is specified (e.g. a date in the past), the cookie will be deleted.
*                             If set to null or omitted, the cookie will be a session cookie and will not be retained
*                             when the the browser exits.
* @option String path The value of the path atribute of the cookie (default: path of page that created the cookie).
* @option String domain The value of the domain attribute of the cookie (default: domain of page that created the cookie).
* @option Boolean secure If true, the secure attribute of the cookie will be set and the cookie transmission will
*                        require a secure protocol (like HTTPS).
* @type undefined
*
* @name $.cookie
* @cat Plugins/Cookie
* @author Klaus Hartl/klaus.hartl@stilbuero.de
*/

/**
* Get the value of a cookie with the given name.
*
* @example $.cookie('the_cookie');
* @desc Get the value of a cookie.
*
* @param String name The name of the cookie.
* @return The value of the cookie.
* @type String
*
* @name $.cookie
* @cat Plugins/Cookie
* @author Klaus Hartl/klaus.hartl@stilbuero.de
*/
jQuery.cookie = function(name, value, options) {
    if (typeof value != 'undefined') { // name and value given, set cookie
        options = options || {};
        if (value === null) {
            value = '';
            options.expires = -1;
        }
        var expires = '';
        if (options.expires && (typeof options.expires == 'number' || options.expires.toUTCString)) {
            var date;
            if (typeof options.expires == 'number') {
                date = new Date();
                date.setTime(date.getTime() + (options.expires * 24 * 60 * 60 * 1000));
            } else {
                date = options.expires;
            }
            expires = '; expires=' + date.toUTCString(); // use expires attribute, max-age is not supported by IE
        }
        // CAUTION: Needed to parenthesize options.path and options.domain
        // in the following expressions, otherwise they evaluate to undefined
        // in the packed version for some reason...
        var path = options.path ? '; path=' + (options.path) : '';
        var domain = options.domain ? '; domain=' + (options.domain) : '';
        var secure = options.secure ? '; secure' : '';
        document.cookie = [name, '=', encodeURIComponent(value), expires, path, domain, secure].join('');
    } else { // only name given, get cookie
        var cookieValue = null;
        if (document.cookie && document.cookie != '') {
            var cookies = document.cookie.split(';');
            for (var i = 0; i < cookies.length; i++) {
                var cookie = jQuery.trim(cookies[i]);
                // Does this cookie string begin with the name we want?
                if (cookie.substring(0, name.length + 1) == (name + '=')) {
                    cookieValue = decodeURIComponent(cookie.substring(name.length + 1));
                    break;
                }
            }
        }
        return cookieValue;
    }
};
