﻿var lightboxBackground;
var lightboxImage;
var previousDocumentOnclick;
function viewImage(imageUrl)
{	

/*	
    lightboxBackground = document.createElement("div");
    lightboxBackground.className="lightboxBackground";
    
    lightboxImage=document.createElement("img");
    lightboxImage.className = "lightboxImage";
    lightboxImage.src=imageUrl;
    
    document.body.appendChild(lightboxBackground);
    document.body.appendChild(lightboxImage);
    
    previousDocumentOnclick = document.body.onclick;
    
    document.body.onclick=closeImage;
    */
    
    //window.open(imageUrl, '_image', 'width=500,height=500,status=no');
}
function closeImage()
{
    document.body.onclick = previousDocumentOnclick;
    document.body.removeChild(lightboxBackground);
    document.body.removeChild(lightboxImage);
}

function openWindow(url,title, w, h, center, windowName) {
    var options = "width=" + w + ",height=" + h + ",";
    options += "resizable=yes,scrollbars=yes,status=yes,";
    options += "menubar=no,toolbar=no,location=no,directories=no";
    var newWin = window.open(url, windowName.split('/').join(''), options);
    newWin.focus();
 }


if (typeof Ext != "undefined") 
{
    Ext.tree.AjaxProTreeLoader = function(config){
        Ext.tree.AjaxProTreeLoader.superclass.constructor.call(this, config);
    };
    Ext.extend(Ext.tree.AjaxProTreeLoader, Ext.tree.TreeLoader, {
        load: function(node, callback) {
            if (this.clearOnLoad) {
                while (node.firstChild) {
                    node.removeChild(node.firstChild);
                }
            }
            if (node.attributes.children) { // preloaded json children
                var cs = node.attributes.children;
                for (var i = 0, len = cs.length; i < len; i++) {
                    node.appendChild(this.createNode(cs[i]));
                }
                if (typeof callback == "function") {
                    callback();
                }
            } else if (node.attributes.ajaxProCall || this.ajaxProCall) {
                this.requestData(node, callback);
            }
        },
        requestData: function(node, callback) {
            if (this.fireEvent("beforeload", this, node, callback) !== false) {
                var argument = { callback: callback, node: node };
                var loader = this;
                var ajaxProCallback = function(response) {
                    response.argument = argument;
                    if (response.error) {
                        return loader.handleFailure(response);
                    }
                    return loader.handleResponse(response);
                };
                if (node.attributes.ajaxProCall) {
                    //root node has a ajaxProCall that gets data for direct children
                    this.transId = true;
                    node.attributes.ajaxProCall(ajaxProCallback);
                }
                else if (this.ajaxProCall) {
                    //non-root node uses the predefined ajaxProCall in the TreeLoader
                    this.transId = true;
                    this.ajaxProCall(node.id, ajaxProCallback);
                }
                else {
                    this.fireEvent('loadexception', this, node, 'no ajaxProCall configured.');
                }
            } else {
                // if the load is cancelled, make sure we notify 
                // the node that we are done
                if (typeof callback == "function") {
                    callback();
                }
            }
        },
        processResponse: function(response, node, callback) {
            try {
                var o = response.value;
                for (var i = 0, len = o.length; i < len; i++) {
                    var n = this.createNode(o[i]);
                    if (n) {
                        node.appendChild(n);

                        if (n.subnodes) {
                            for (var j = 0, len = n.subnodes.length; j < len; j++) {
                                var s = this.createNode(n.subnodes[j]);
                                if (s) {
                                    n.appendChild(s);
                                }
                            }
                        }
                    }
                }
                if (typeof callback == "function") {
                    callback(this, node);
                }
            } catch (e) {
                this.handleFailure(response);
            }
        }
    });
}

//TODO: There is some problems with arrow right and arrow left key. The functionality works as it should if I remove return false, from KeyCheck. But the grid is moving
//left or right depending on key press. To fix that problem I tried to return false on onkeyup and onkeydown events. That fixes the problem with the moving grid. But when 
// the playlist reaches the end or start of the list, and are moving to the other end of the list, an error occurs.
document.onkeyup = disableKey;
document.onkeydown = function KeyCheck(e) {
    var keyEvent = window.event? event: e;
    //alert("KeyEvent: " + keyEvent);
    var KeyID = keyEvent.keyCode;
    //alert("KeyId : " + KeyID);
    if(document.getElementById("flashPlayerContentWrapper").style.display != "block")
    {
        switch (KeyID) {
            case 37:
                //Left arrow key press.
                previous();
                return false;
                break;
            case 39:
                //Right arrow key press.
                next();
                return false;
                //disableKey();
                break;
        }
    }
}

function disableKey(e) {
    var keyEvent = window.event ? event : e;
    var KeyID = keyEvent.keyCode;
    if (document.getElementById("flashPlayerContentWrapper").style.display != "block") {
        switch (KeyID) {
            case 37:
                //Left arrow key press.
                return false;
                break;
            case 39:
                //Right arrow key press.
                return false;
                //disableKey();
                break;
        }
    }
}

function getFlashMovieObject(movieName) {
    if (window.document[movieName]) {
        return window.document[movieName];
    }
    if (navigator.appName.indexOf("Microsoft Internet") == -1) {
        if (document.embeds && document.embeds[movieName])
            return document.embeds[movieName];
    }
    else // if (navigator.appName.indexOf("Microsoft Internet")!=-1)
    {
        return document.getElementById(movieName);
    }
}

var currentPlayButton;
var currentSound;
var player;
//Set sound and playbutton that are currently active.
function setCurrentSound(soundId) {
    currentSound = soundId;
    currentPlayButton = 'play' + currentSound;
}
var playlist = new Array();

var nextIndex = 0;

function playSound_impl(soundUrl, element) {
    // this is needed because if the flash isn't visible when startin playing the sound will be muted.
    //	        if (soundUrl) {
    //	            wrapper.dom.style.position = 'fixed';
    //	            wrapper.dom.style.top = 200;
    //	            wrapper.dom.style.right = 200;
    //	            wrapper.frame();
    //	            //setTimeout(function(){wrapper.dom.style.position = 'relative';}, 500);
    //	            
    //	        }

    var agent = navigator.userAgent.toLowerCase();
    var isIosDevice = (agent.indexOf("iphone") > -1 || agent.indexOf("ipad") > -1 || agent.indexOf("ipod") > -1);
    if (isIosDevice) {
        document.getElementById("footerHolder").setAttribute("class", "ios_footer");
    }

    var calculatedSoundUrl = soundUrl;
    if (document.domain === "localhost" || document.domain === "stockmusic.iteam.se") {
        calculatedSoundUrl = "http://www.stockmusic.com" + soundUrl;
    }

    var a = document.createElement('audio');
    var hasAudioMp3Support = (!!(a.canPlayType && a.canPlayType('audio/mpeg;').replace(/no/, '')));

    if (hasAudioMp3Support) {
        if (soundUrl) {
            var audio = document.getElementById("audioPlayerControl");
            audio.setAttribute("src", calculatedSoundUrl);
            audio.setAttribute("class", null);
            audio.play();
            console.log("Playing sound, soundUrl: " + calculatedSoundUrl);
        }
    } else {
        var flashvars = {
            src: calculatedSoundUrl,
            shortcuts: "yes",
            volume: 75,
            autostart: "yes"
        };
        var params = {
            bgcolor: "#6c6d6e"
        };
        var attributes = {};

        player = swfobject.embedSWF("/Javascript/emff_stuttgart.swf", "flashPlayerContentWrapper", "150", "30", "8.0.0", "expressInstall.swf", flashvars, params, attributes);
    }

    try {
        var wrapper = Ext.get('flashPlayerContentWrapper');
        wrapper.frame();
    } catch (e) { }

    if (element != null) {
        //	            var cartWrapper = Ext.get('flashPlayerContentWrapper');
        //                var x = cartWrapper.getX();
        //                var y = cartWrapper.getY();
        ////                Ext.fly(element).createProxy("play", document.body, true).show().shift({ x: x, y: y, callback: function(element) { Ext.fly('flashPlayerContentWrapper').frame(); } });
        ////                Ext.fly(document.body.appendChild(element.cloneNode(true))).set("z-index", "10000").show().shift({ x: x, y: y, callback: function(element) { Ext.fly('flashPlayerContentWrapper').frame(); } });
        //                var flyingButton = Ext.get(document.body.appendChild(element.cloneNode(true))).show();
        //                flyingButton.position('absolute', 100000);
        //                flyingButton.setXY(Ext.get(element).getXY());
        //                flyingButton.shift({ x: x, y: y, callback: function(element) { Ext.get('flashPlayerContentWrapper').frame(); } });

        // Ext.get('flashPlayerContentWrapper').frame();
    }
}

function stopSound_impl() {
    try {
        var audio = document.getElementById("audioPlayerControl");
        if (audio && audio.src) {
            audio.pause();
        }

        playSound_impl("");
        document.getElementById("flashPlayerContentWrapper").style.display = 'none';
        document.getElementById("flashPlayer").style.display = 'none';
    } catch(e){
    }
}

function fill_playlist(thePlaylist) {
    for (var i = 0; i < thePlaylist.length; i++) {
        playlist[i] = thePlaylist[i].id.slice(4);
    }
}

function previous() {
    var currentIndex = 0;
    for (var i = 0; i < playlist.length; i++) {
        if (playlist[i] == currentSound) {
            currentIndex = i;
            break;
        }
    }
    var soundId = null;
    setLastPlayedSoundId(currentSound);
    resetPlayButton();
    if (currentIndex - 1 >= 0) {
        setCurrentSound(playlist[currentIndex - 1]);
        playsound(currentSound, false, this);
    }
    else {
        setCurrentSound(playlist[playlist.length - 1]);
        playsound(currentSound, false, this);
    }
}

//Move to next sound in playlist.
function next() {
    for (var i = 0; i < playlist.length; i++) {
        if (playlist[i] == currentSound) {
            currentIndex = i;
            break;
        }
    }
    var soundId = null;
    setLastPlayedSoundId(currentSound);
    resetPlayButton();
    if (currentIndex + 1 <= playlist.length - 1) {
        setCurrentSound(playlist[currentIndex + 1]);
        playsound(currentSound, false, this);
    }
    else {
        setCurrentSound(playlist[0]);
        playsound(currentSound, false, this);
    }
}




/* To Title Case 1.1.1
* David Gouch <http://individed.com>
* 23 May 2008
* License: http://individed.com/code/to-title-case/license.txt
*
* In response to John Gruber's call for a Javascript version of his script: 
* http://daringfireball.net/2008/05/title_case
*/

String.prototype.toTitleCase = function () {
    return this.replace(/([\w&`'‘’"“.@:\/\{\(\[<>_]+-? *)/g, function (match, p1, index, title) {
        if (index > 0 && title.charAt(index - 2) !== ":" &&
        	match.search(/^(a(nd?|s|t)?|b(ut|y)|en|for|i[fn]|o[fnr]|t(he|o)|vs?\.?|via)[ \-]/i) > -1)
            return match.toLowerCase();
        if (title.substring(index - 1, index + 1).search(/['"_{(\[]/) > -1)
            return match.charAt(0) + match.charAt(1).toUpperCase() + match.substr(2);
        if (match.substr(1).search(/[A-Z]+|&|[\w]+[._][\w]+/) > -1 ||
        	title.substring(index - 1, index + 1).search(/[\])}]/) > -1)
            return match;
        return match.charAt(0).toUpperCase() + match.substr(1);
    });
};


