/**************************************************
 * IS24 Video Sharing, JS Bibliothek V0.1 BETA
 * Video Object
 * Arguments (*are mandatory)
 *    videoid*: the id of the video
 *    divLayerName*: layer id where the player should be rendered
 *    width: width of the player (not layer)
 *    height: height of the player (not layer)
 *    additionalElements: additional element(s) which will be added after the flash player
 *                        example: document.getElementById("[element name]")
 *    customStillImage: URL of the image which will be shown in player before playing the video
 *                      host name and protocol are optional, port 80 is mandatory
 *    clickOnDisplay: URL to which the browser will be forwarded if the user cklicks the player display
 *                      host name and protocol are optional, port 80 is mandatory
 *
 **************************************************/
function VideoObject(videoid, divLayerName, width, height, additonalElements, customStillImage, clickOnDisplay, showErrors, popUpTargetName, designData) {
    var flashPlayerDivName = divLayerName;										//div layer for flash player
    var errorMessagesDivName = divLayerName;										//div layer for error messages
    var flashPlayerId = "flashplayer" + videoid;									//id of flash player object
    var originInnerHTML;															//original inner HTML before any changes
    var videoURL;																	//URL for player
    var additionalLayerElements = additonalElements;								//additonal elements whcih will be displayed below the player
    var refreshTimeoutThread;														//private refresh timer in case of errorness video responses      
    var followDisplayURL = "";													//URL for redirecting the browser on display klick event
    var customImage = "";															//URL of sutomized still image shown in player
    var showTechnicalErrors = false;
    var targetWindowName = "";
    var _designData = designData;
    var clickOnDisplayFunction = function () {
    };

    if (null != popUpTargetName && typeof popUpTargetName != "undefined") {
        targetWindowName = popUpTargetName;
    }

    if (null != showErrors && typeof showErrors != "undefined") {
        showTechnicalErrors = showErrors;
    }

    if (null != clickOnDisplay && typeof clickOnDisplay != "undefined") {
        if (typeof clickOnDisplay === "function") {
            clickOnDisplayFunction = clickOnDisplay;
        }
        else if (clickOnDisplay.indexOf(window.location.host) == -1 && clickOnDisplay.indexOf("http") == -1) {    //check of http, because picture can be on other server than caller
            followDisplayURL = window.location.protocol + "//" + window.location.host + clickOnDisplay;
        } else {
            followDisplayURL = clickOnDisplay;
        }
    }

    if (null != customStillImage && typeof customStillImage != "undefined") {
        if (customStillImage.indexOf(window.location.host) == -1 && customStillImage.indexOf("http") == -1) {    //check of http, because picture can be on other server than caller
            customImage = window.location.protocol + "//" + window.location.host + customStillImage;
        } else {
            customImage = customStillImage;
        }
    }

    if (typeof originInnerHTML == "undefined") {                                   //make origin backup only in during first call
        originInnerHTML = document.getElementById(flashPlayerDivName).innerHTML;  	//private DIV content at startup          
    }

    this.videoid = videoid;														//public  videoid      
    var videoWidth;
    if (typeof width != "undefined") {
        videoWidth = width;
    } else {
        videoWidth = VideoSharing.defaultVideoWidth;								//use default settings if nothing is set
    }

    var videoHeight;
    if (typeof width != "undefined") {
        videoHeight = height;
    } else {
        videoHeight = VideoSharing.defaultVideoHeight;								//use default settings if nothing is set
    }

    /**************************************************
     * createFlashPlayerWithURL(div, url)
     * Function renders the div element with flash player data.
     * The use of dynamic object creation does not work with IE7,
     * so lets change to old working art of innerHTML.
     * Arguments:
     * div is the div element to show the player in
     * url is the video URL for the player
     **************************************************/
    var getPlayerHTMLCode = function (videoWidth, videoHeight, isZoom) {
        var videoUrlWithFlashVerion = appendFlashVersion(videoURL);
        var encodedVideoURL = "";

        if (customImage.length > 0) {
            var encodedURI = customImage.replace(/:/, "%3A");
            encodedURI = encodedURI.replace("?", "%3F");
            encodedVideoURL = "" + videoUrlWithFlashVerion + "&customimage=" + encodedURI;
        } else {
            encodedVideoURL = videoUrlWithFlashVerion;
        }

        var dummyVideoID = "flashPlayer";
        var preHTML = "";
        var postHTML = "";
        var wmode = "window";
        var playerHTML = "";

        if (_designData) {
            if (_designData.wmode) {
                wmode = _designData.wmode;
            }
            if (!isZoom) {
                if (_designData.playerHTMLPreHTML) {
                    preHTML = _designData.playerHTMLPreHTML;
                }
                if (_designData.playerHTMLPostHTML) {
                    postHTML = _designData.playerHTMLPostHTML;
                }
            }
        }

        playerHTML += preHTML;
        playerHTML += "<object  ";	//id=\"" + /*IE7 BUG videoid*/ dummyVideoID + "\"
        playerHTML += "width=\"" + videoWidth + "\"   height=\"" + videoHeight + "\"  align=\"middle\" ";
        playerHTML += "codebase=\"http://fpdownload.macromedia.com/pub/shockwave/cabs/flash/swflash.cab#version=8,0,0,0\"  ";
        playerHTML += "classid=\"clsid:d27cdb6e-ae6d-11cf-96b8-444553540000\" > ";
        playerHTML += "  <param value=\"always\" name=\"allowScriptAccess\"/> ";
        playerHTML += "  <param value=\"" + encodedVideoURL + "\" name=\"movie\"/> ";
        playerHTML += "  <param value=\"high\" name=\"quality\"/> ";
        playerHTML += "  <param value=\"noscale\" name=\"scale\"/> ";
        playerHTML += "  <param value=\"" + wmode + "\" name=\"wmode\"/> ";
        playerHTML += "  <param value=\"#000000\" name=\"bgcolor\"/> ";

        playerHTML += " <embed width=\"" + videoWidth + "\" height=\"" + videoHeight + "\" align=\"middle\"";
        playerHTML += " pluginspage=\"http://www.macromedia.com/go/getflashplayer\" type=\"application/x-shockwave-flash\"  ";
        playerHTML += " allowscriptaccess=\"always\" name=\"" + /*IE7 BUG videoid*/ dummyVideoID + "\"  ";
        playerHTML += " bgcolor=\"#000000\" wmode=\"" + wmode + "\" scale=\"noscale\" quality=\"high\"  ";
        playerHTML += " src=\"" + encodedVideoURL + "\"/> ";
        playerHTML += " </object>";
        playerHTML += postHTML;


        return playerHTML;
    };

    /*******************************************
     * Tries to determines the version of the flash-plugin of the client.
     * If no plugin is available or the version could not be determined
     * the origin videoUrl provided by parameter gets returned.
     *
     * If the version could be determined it is appended to the videoUrl parameter and returned.
     *******************************************/
    function appendFlashVersion(url) {
        var flashversion = "0.0.0";
        var flashplugin = navigator.plugins["Shockwave Flash"];
        if (flashplugin) {
            var description = flashplugin.description;
            if (description) {
                flashversion = description.substring(description.indexOf("Flash ") + 6, 30).replace("r", ".");
                flashversion = flashversion.replace(/\s/g, '');

                return url + "%26flashversion%3D" + flashversion;
            }
        }

        return url;
    }

    /**************************************************
     * Used as AJAX Call back function for processing the fetched
     * Video URL as server response
     **************************************************/
    this.processVideoURL = function (response) {
        var div = document.getElementById(flashPlayerDivName);
        var responseURL = response.responseText;

        if (response.status != "200") {
            if (showTechnicalErrors) {
                var tecErrHtml = "";
                if (_designData && _designData.unaviableProcessImagePreHTML) {
                    tecErrHtml = _designData.unaviableProcessImagePreHTML;
                }

                tecErrHtml += "<img src=\"" + VideoSharing.unaviableProcessImage + "\" alt=\"" + VideoSharing.unaviableProcessImageALT + "\">";

                if (_designData && _designData.unaviableProcessImagePostHTML) {
                    tecErrHtml += _designData.unaviableProcessImagePostHTML;
                }
                div.innerHTML = tecErrHtml;
            } else {
                return;	//do not any changes
            }
        }

        if (typeof responseURL != "undefined" && responseURL.length > 1) {
            videoURL = responseURL;
            var playerHTML = getPlayerHTMLCode(videoWidth, videoHeight);
            //div.innerHTML = playerHTML;
            if (null != additionalLayerElements && typeof additionalLayerElements != "undefined") {
                //div.appendChild(additionalLayerElements);
                playerHTML += additionalLayerElements;
            }
            div.innerHTML = playerHTML;
            /* Hack the IE "click to activate and use this control"*/
            if (is24_isIE) {
                enableUseOfEmbededObjectInIE(div);
            }
        } else {
            var status = getStatusFromHeader(response);

            if (status.indexOf("wrongFileFormat") > -1) {
                /*
                 *	Show the failed convertation of image because of wrong file format, leave, no further processing needed
                 */
                var wrngFileFormatHtml = "";
                if (_designData && _designData.wrongFileFormatImagePreHTML) {
                    wrngFileFormatHtml = _designData.wrongFileFormatImagePreHTML;
                }

                wrngFileFormatHtml += "<img src=\"" + VideoSharing.wrongFileFormatImage + "\" alt=\"" + VideoSharing.wrongFileFormatImageALT + "\">";

                if (_designData && _designData.wrongFileFormatImagePostHTML) {
                    wrngFileFormatHtml += _designData.wrongFileFormatImagePostHTML;
                }
                div.innerHTML = wrngFileFormatHtml;
                return;
            }

            if (!showTechnicalErrors) {
                /*
                 *	no details showing is enabled, just refetch the URL and leave
                 *	This is typically for all expose result lists and details (gallery view, picture Tab...)
                 */
                refetchURL();
                return;
            }

            /* PROCESS SHOW TECHNICAL ERRORS MODE */
            if (status.indexOf("processing") > -1 || status.indexOf("incoming") > -1) {
                /*
                 *	Show the Processing image and refetch the URL
                 */
                var cnvrtProcessHtml = "";
                if (_designData && _designData.convertProcessImagePreHTML) {
                    cnvrtProcessHtml = _designData.convertProcessImagePreHTML;
                }

                cnvrtProcessHtml += "<img src=\"" + VideoSharing.convertProcessImage + "\" alt=\"" + VideoSharing.convertProcessImageALT + "\">";

                if (_designData && _designData.convertProcessImagePostHTML) {
                    cnvrtProcessHtml += _designData.convertProcessImagePostHTML;
                }
                div.innerHTML = cnvrtProcessHtml;
                refetchURL();
            } else if (showTechnicalErrors && (status.indexOf("failed") > -1 )) {
                /*
                 *	Show the Faild image and leave (no further processing needed
                 */
                var fldProcesHtml = "";
                if (_designData && _designData.failedProcessImagePreHTML) {
                    fldProcesHtml = _designData.failedProcessImagePreHTML;
                }

                fldProcesHtml += "<img src=\"" + VideoSharing.failedProcessImage + "\" alt=\"" + VideoSharing.failedProcessImageALT + "\">";

                if (_designData && _designData.failedProcessImagePostHTML) {
                    fldProcesHtml += _designData.failedProcessImagePostHTML;
                }

                div.innerHTML = fldProcesHtml;
            } else {
                /*
                 *	Unknown Error, just refetch the URL
                 */
                refetchURL();
            }
        }
    };

    enableUseOfEmbededObjectInIE = function (divLayer) {
        if (divLayer.hasChildNodes()) {
            for (i = 0; i < divLayer.children.length; i++) {
                var object_element = divLayer.children[i];
                if (typeof object_element == "object") {
                    object_element.outerHTML = object_element.outerHTML;
                }
            }
        }
    };

    getStatusFromHeader = function (response) {
        var status = response.getResponseHeader["status"];
        try {
            checkStatus(status);
            return status;
        } catch (er) {/*ignore here*/
        }

        status = response.getResponseHeader["Status"];	//use case senstive status
        try {
            checkStatus(status);
            return status;
        } catch (er) {
            return "failed";
        }
    };

    checkStatus = function (status) {
        if (status == null || typeof status == "undefined") {
            throw "Status is undefined";
        }
    };

    /**************************************************
     * Restores the DIV origin data
     **************************************************/
    restoreDisplay = function () {
        var div = document.getElementById(flashPlayerDivName);
        div.innerHTML = originInnerHTML;
        if (typeof refreshTimeoutThread != "undefined") {
            window.clearTimeout(refreshTimeoutThread);
        }
    };

    /**************************************************
     * Process error from Server
     * The method will ingore all errors and will refetch
     * the video URL. This will be done at least defined
     * reconnect times.
     **************************************************/
    var retryCount = 0;
    this.handleFailure = function (response) {
        refetchURL(response);
    };

    /**************************************************
     * Makes a fetch URL aysnch request if max retry count
     * not exeeded
     **************************************************/
    var refetchURL = function () {
        retryCount++;
        if (retryCount <= VideoSharing.retryURLFetchesCount) {
            var clickOn;

            if (followDisplayURL.length == 0) {
                clickOn = clickOnDisplayFunction;
            } else {
                clickOn = followDisplayURL;
            }

            refreshTimeoutThread = window.setTimeout(function () {
                        VideoSharing.fetchVideoData(videoid, flashPlayerDivName,
                                width, height, additonalElements, customStillImage, clickOn, showErrors);
                    },
                    VideoSharing.refreshVideoStatusTimeout);
        } else {
            if (showTechnicalErrors) {
                var div = document.getElementById(flashPlayerDivName);
                var fldProcesHtml = "";
                if (_designData && _designData.failedProcessImagePreHTML) {
                    fldProcesHtml = _designData.failedProcessImagePreHTML;
                }

                fldProcesHtml += "<img src=\"" + VideoSharing.failedProcessImage + "\" alt=\"" + VideoSharing.failedProcessImageALT + "\" >";

                if (_designData && _designData.failedProcessImagePostHTML) {
                    fldProcesHtml += _designData.failedProcessImagePostHTML;
                }
                div.innerHTML = fldProcesHtml;
            } else {
                restoreDisplay();
            }
            window.clearTimeout(refreshTimeoutThread);
        }
    };

    /**************************************************
     * Shows the video in a 640x480 px Panel (modal)
     **************************************************/
    var videoPanel;
    this.handelZoomKlick = function () {
        if (typeof videoPanel != "undefined") {
            videoPanel.show();
        } else {
            videoPanel = new YAHOO.widget.Panel("videopanel" + this.videoid,
                    { width:"600px",
                        height:"530px",
                        fixedcenter:true,
                        close:true,
                        draggable:true,
                        modal:true,
                        visible:true
                    }
            );
            bodyString = getPlayerHTMLCode(600, 510, true);

            //is content of image defined in videoservice.css videoPanel.setHeader("Schließen");
            if (_designData && _designData.headerDivision) {
                videoPanel.setHeader(_designData.headerDivision);
            } else {
                videoPanel.setHeader("");
            }

            videoPanel.setBody(bodyString);
            videoPanel.render(document.body);
        }
    };

    /**************************************************
     * Redirects the Browser to given URL
     **************************************************/
    this.handelDisplayKlick = function () {
        if (followDisplayURL.length == 0) {
            clickOnDisplayFunction();
            return;	//no URL avaiable
        }

        if (targetWindowName.length > 0) {
            VideoSharing.open_window(followDisplayURL, 'expimage', 820, 750, 'resizable=1,scrollbars=1,toolbar=1,status=0,menubar=1,location=0,directories=0')
        } else {
            document.location.href = followDisplayURL;
        }
    }
}

