var WOGAppConfig = function() {
    var t = this;
    t.UpperTabsClientId = null;
    t.UpperTabsInfoTabIndex = null;
    t.InfoPageUrl = null;
    t.LowwerTabsClientId = null;
    t.LowwerTabsRecordingsSeriesTabIndex = null;
    t.RecordingsSeriesPageUrl = null;
    t.CultureApplicationSuffix = 'GR',
    t.CultureParentName = 'el';
}

var _WOGAppConfig = new WOGAppConfig();

var ImgSrc = {
    suffixes: { 'pressed': '_pressed', 'mouseon': '_mouseover' },

    remSuffix: function(src, srcSuffix) {
        if (srcSuffix != null) {
            var re = new RegExp(srcSuffix, "ig");
            src = src.replace(re, '');
            return src;
        }
        else {
            for (var elem in ImgSrc.suffixes) {
                var re = new RegExp(elem, "ig");
                src = src.replace(re, '');
            }
            return src;
        }
    },

    addSuffix: function(src, srcSuffix) {
        //if (ImgSrc.testSuffixes(src)) return;

        var srcSplit = src.split('.');

        if (srcSplit.length > 1) {
            srcSplit[srcSplit.length - 2] = srcSplit[srcSplit.length - 2] + srcSuffix;
        }
        src = srcSplit.join('.');

        return src;
    },

    testSuffixes: function(src) {
        var bContains = false;
        for (var elem in ImgSrc.suffixes) {
            var re = new RegExp(elem, "ig");
            bContains = bContains || re.test(src);
        }
        return bContains;
    },

    preload: function(src) {
        var imgNew = new Image();
        imgNew.src = src;
    }
}


var WOGStreaming = function() {
    var t = this;

    t.streamLive = { 'HIGH': null, 'MEDIUM': null, 'LOW': null };
    t.bitrate = { 'HIGHER': null, 'HIGH': null, 'MEDIUM': null, 'LOW': null };


    t.__currentQuality = 'high';
    t.get_currentQuality = function() { return t.__currentQuality; };
    t.set_currentQuality = function(value) { if (value != null) t.__currentQuality = value; };

    t.__currentInfoQuery = null;
    t.get_InfoQuery = function() { return t.__currentInfoQuery; };
    t.set_InfoQuery = function(value) { t.__currentInfoQuery = value; };


    t.isLiveStream = function(streamUrl) {
        streamUrl = streamUrl.toLowerCase();
        var isLive = false;

        if (streamUrl == t.streamLive.LOW.toLowerCase())
            isLive = true;
        else if (streamUrl == t.streamLive.MEDIUM.toLowerCase())
            isLive = true;
        else if (streamUrl == t.streamLive.HIGH.toLowerCase())
            isLive = true;

        return isLive;
    };

    t.getSourceForLive = function(quality) {
        var src = null;
        quality = quality.toLowerCase();
        switch (quality) {
            case 'low': src = t.streamLive.LOW; break;
            case 'medium': src = t.streamLive.MEDIUM; break;
            case 'high': src = t.streamLive.HIGH; break;
        }
        return src;
    };

    t.getSourceForOnDemand = function(quality, src) {
        //_32kbps.wmv
        if (src == null) return src;

        var bitrate = null;
        var ndxUnderScr = src.lastIndexOf('_');
        if (src.toLowerCase().indexOf('kbps.wmv') > ndxUnderScr) {
            switch (quality) {
                case 'low': bitrate = t.bitrate.LOW; break;
                case 'medium': bitrate = t.bitrate.MEDIUM; break;
                case 'high': bitrate = t.bitrate.HIGH; break;
            }
        }

        if (bitrate != null) {
            var srcSplit = src.split('_');
            if (srcSplit.length > 1) {
                srcSplit[srcSplit.length - 1] = bitrate + 'kbps.wmv';
            }
            src = srcSplit.join('_');
        }

        return src;
    }
}

var _WOGStreaming = new WOGStreaming();

function preloadImg(imgSrc) { var imgNew = new Image(); imgNew.src = imgSrc; }

var WOGBitratesSwitch = function() {
    var t = this;
    t.imgId = {
        'HIGH': null,   // image source. image indicator for high quality stream
        'MEDIUM': null, // image source. image indicator for medium quality stream
        'LOW': null     // image source. image indicator for low quality stream
    };

    t.swapImages = function(imgId) {
        var img = document.getElementById(imgId);

        if (isExistingObj(img)) {
            var src = img.src.toLowerCase();

            if (src.indexOf(ImgSrc.suffixes['pressed']) > -1)
                src = ImgSrc.remSuffix(src, ImgSrc.suffixes['pressed']);
            else
                src = ImgSrc.addSuffix(src, ImgSrc.suffixes['pressed']);

            img.src = src;
        }
    }

    t.preloadImages = function() {
        var img = document.getElementById(t.imgId.HIGH);
        if (isExistingObj(img)) { setTimeout(function() { preloadImg(ImgSrc.addSuffix(img.src, ImgSrc.suffixes['pressed'])); }, 1000); }

        img = document.getElementById(t.imgId.MEDIUM);
        if (isExistingObj(img)) { setTimeout(function() { preloadImg(ImgSrc.addSuffix(img.src, ImgSrc.suffixes['pressed'])); }, 1000); }

        img = document.getElementById(t.imgId.LOW);
        if (isExistingObj(img)) { setTimeout(function() { preloadImg(ImgSrc.addSuffix(img.src, ImgSrc.suffixes['pressed'])); }, 1000); }
    }

    t.resetImages = function() {
        var img = document.getElementById(t.imgId.HIGH);
        if (isExistingObj(img)) img.src = ImgSrc.remSuffix(img.src, ImgSrc.suffixes['pressed']);

        img = document.getElementById(t.imgId.MEDIUM);
        if (isExistingObj(img)) img.src = ImgSrc.remSuffix(img.src, ImgSrc.suffixes['pressed']);

        img = document.getElementById(t.imgId.LOW);
        if (isExistingObj(img)) img.src = ImgSrc.remSuffix(img.src, ImgSrc.suffixes['pressed']);
    }

    t.setQuality = function(quality) {
        t.resetImages();
        quality = quality.toLowerCase();
        switch (quality) {
            case 'low': t.swapImages(t.imgId.LOW); break;
            case 'medium': t.swapImages(t.imgId.MEDIUM); break;
            case 'high': t.swapImages(t.imgId.HIGH); break;
        }
    }
}

var _WOGBrSwitch = new WOGBitratesSwitch();


var ClientStationProgram = function() {
    var t = this;
    t.dummy = function() { return Math.floor(Math.random() * 10000); };
    t.localtime = function() { return new Date().toString(); };

    t.loadStationProgram = function(controlId, iRefreshPeriod) {
        WordOfGod.gr.StationProgram.GetProgram(_WOGAppConfig.CultureApplicationSuffix, t.dummy(), t.localtime(), "''", t.localtime(), "''", "0", "0", /* parameters */function(result, eventArgs) { CallBackDelegate.Succeeded(result, eventArgs, controlId); }, function(error) { CallBackDelegate.Failed(error, controlId); }, null);
        if (iRefreshPeriod > 10000) {
            var func = 'refreshStationProgram("' + controlId + '", ' + iRefreshPeriod + ');';
            setTimeout(func, iRefreshPeriod);
        }
    };

    t.loadSermons = function(controlId, iRefreshPeriod) {
        WordOfGod.gr.StationProgram.GetSermons(_WOGAppConfig.CultureApplicationSuffix, t.dummy(), t.localtime(), "''", t.localtime(), "''", "0", "0", /* parameters */function(result, eventArgs) { CallBackDelegate.Succeeded(result, eventArgs, controlId); }, function(error) { CallBackDelegate.Failed(error, controlId); }, null);
        if (iRefreshPeriod > 10000) {
            var func = 'refreshSermons("' + controlId + '", ' + iRefreshPeriod + ');';
            setTimeout(func, iRefreshPeriod);
        }
    };
}

function refreshSermons(lblSermonsDataId, iRefreshPeriod) {
    var a = new ClientStationProgram();
    a.loadSermons(lblSermonsDataId, iRefreshPeriod);

    a = null;
}

function refreshStationProgram(lblProgramDataId, iRefreshPeriod) {
    var a = new ClientStationProgram();
    a.loadStationProgram(lblProgramDataId, iRefreshPeriod);

    a = null;
}

var CallBackDelegate = {
    // This is the callback function invoked if the Web service succeeded.
    // It accepts the result object as a parameter.
    Succeeded: function(result, eventArgs, elemId) {
        // Page element to display feedback.
        if (result != "NOCHANGE") {
            var RsltElem = document.getElementById(elemId);
            if (RsltElem.tagName == "IFRAME") 
                fillFrame(elemId, result);
            else
                RsltElem.innerHTML = result;
        }
        //var a = new Sys.UI.MyControl(RsltElem);
        //a.removeCssClass('loading');
    },


    // This is the callback function invoked if the Web service failed.
    // It accepts the error object as a parameter.
    Failed: function(error, elemId) {
        // Display the error.
        var content = "Service error: " + error.get_message();
        var RsltElem = document.getElementById(elemId);
        if (RsltElem.tagName == "IFRAME") 
            fillFrame(elemId, content);
        else
            RsltElem.innerHTML = content;
        //var a = new Sys.UI.MyControl(RsltElem);
        //a.removeCssClass('loading');
    }
}



var MediaPlayerWrapper = function() {
    var t = this;
    t.plrObj = null;
    t.__plrDomId = null;


    t.get_playerId = function() { return t.__plrDomId; };
    t.set_playerId = function(value) { t.__plrDomId = value; };

    t.getApplicationPlayer = function() {
        //var plr = getPlayerObj();

        if (t.plrObj) return;
        var cmpnts = Sys.Application.getComponents();
        for (i = 0; i < cmpnts.length; i++) {
            if (cmpnts[i].get_id().indexOf(t.__plrDomId) > -1) {
                t.plrObj = cmpnts[i];
                break;
            }
        }
    };

    t.isPlayerAvailable = function() {
        t.getApplicationPlayer();
        if (t.plrObj) return true;

        return false;
    };

    t.getPlayerObj = function() {
        var playerObj = null;
        var objs = document.getElementsByTagName("OBJECT");
        for (i = 0; i < objs.length; i++) {
            var id = objs[i].id;
            if (id.indexOf("MediaPlayer") > -1)
                playerObj = objs[i];
        }

        return playerObj;
    };

    t.setMediaSource = function(streamUrl) {
        t.getApplicationPlayer();
        if (t.plrObj) {
            try {
                t.plrObj.set_lBalanceText(_WOGAppConfig.CultureApplicationSuffix);
                t.plrObj._setProperties("text", ["LBalanceTextBlock"], t.plrObj.get_lBalanceText());
            } 
            catch (e) { }
            if (streamUrl != playerWrapper.getMediaSource())
                t.plrObj.set_mediaSource(streamUrl);
        }
    };

    t.getMediaSource = function() {
        var src;
        t.getApplicationPlayer();
        if (t.plrObj) src = t.plrObj.get_mediaSource();
        return src;
    };
}

var playerWrapper = new MediaPlayerWrapper();



var _mediaSrc = function(streamUrl, sInfoQuery) {
    if (_WOGStreaming.isLiveStream(streamUrl) == true)
        streamUrl = _WOGStreaming.getSourceForLive(_WOGStreaming.get_currentQuality());
    else
        streamUrl = _WOGStreaming.getSourceForOnDemand(_WOGStreaming.get_currentQuality(), streamUrl);
        
    _WOGStreaming.set_InfoQuery(sInfoQuery);

    if (streamUrl != null)
        playerWrapper.setMediaSource(streamUrl);

    if (sInfoQuery != null) {
        sInfoQuery = sInfoQuery + '&qlt=' + _WOGStreaming.get_currentQuality();
        setTimeout(function() { _setInfoForMedia(sInfoQuery); }, 6000);
    }
}

var getLive = function(quality) {
    if (quality == null) quality = _WOGStreaming.get_currentQuality();

    var streamUrl = _WOGStreaming.getSourceForLive(quality);
    if (streamUrl != null) {
        playerWrapper.setMediaSource(streamUrl);
        var sInfoQuery = 'mediaid=0';
        setTimeout(function() { _setInfoForMedia(sInfoQuery); }, 4000);
    }
}

var getStream = function(quality) {
    var streamUrl = playerWrapper.getMediaSource();
    _WOGStreaming.set_currentQuality(quality);

    if (_WOGStreaming.isLiveStream(streamUrl)) {
        //change live stream
        getLive(quality);
    }
    else {
        //change on demand stream
        streamUrl = _WOGStreaming.getSourceForOnDemand(quality, streamUrl);
        if (streamUrl != null)
            playerWrapper.setMediaSource(streamUrl);

        var sInfoQuery = _WOGStreaming.get_InfoQuery();
        if (sInfoQuery != null) {
            sInfoQuery = sInfoQuery + '&qlt=' + quality;
            setTimeout(function() { _setInfoForMedia(sInfoQuery); }, 6000);
        }
    }

    // change image src
    _WOGBrSwitch.setQuality(quality);
}


var _downLoadSrc = function(sPath) {
    var ifrm = document.getElementById('_downloadMedia');
    if (ifrm)
        ifrm.setAttribute("src", sPath);
    else
        makeFrame(sPath);
};

var _setInfoForMedia = function(sQuery) {
    var tabContainer = $get(_WOGAppConfig.UpperTabsClientId);
    if (!isExistingObj(tabContainer)) return;

    tabContainer = tabContainer.control;
    if (sQuery != 'mediaid=0') tabContainer.set_activeTabIndex(_WOGAppConfig.UpperTabsInfoTabIndex);

    var iframe = tabContainer.get_element().getElementsByTagName('IFRAME');
    if (iframe.length > 0) {
        iframe = iframe['ifrInfo'];
        iframe.setAttribute("src", _WOGAppConfig.InfoPageUrl + '?lang=' + _WOGAppConfig.CultureParentName + '&' + sQuery);
    }
};

var _setRecordingsSeries = function(sQuery) {
    var tabContainer = $get(_WOGAppConfig.LowwerTabsClientId);
    if (!isExistingObj(tabContainer)) return;
    tabContainer = tabContainer.control;
    tabContainer.set_activeTabIndex(_WOGAppConfig.LowwerTabsRecordingsSeriesTabIndex);
    var iframe = tabContainer.get_element().getElementsByTagName('IFRAME');
    if (iframe.length > 0) {
        iframe = iframe['ifrSeries'];
        iframe.setAttribute("src", _WOGAppConfig.RecordingsSeriesPageUrl + '?lang=' + _WOGAppConfig.CultureParentName + '&' + sQuery);
    }
};

function makeFrame(src) {
    var ifrm = document.createElement("IFRAME");
    ifrm.setAttribute("id", '_downloadMedia');
    ifrm.setAttribute("src", src);
    ifrm.style.width = 0 + "px";
    ifrm.style.height = 0 + "px";
    document.body.appendChild(ifrm);
}

function fillFrame(frmId, sFilling) {
    var ifrm = document.getElementById(frmId);
    if (isExistingObj(ifrm)) {
        ifrm = (ifrm.contentWindow) ? ifrm.contentWindow : (ifrm.contentDocument.document) ? ifrm.contentDocument.document : ifrm.contentDocument;

        var doc = ifrm.document;
        var bodies = doc.getElementsByTagName("BODY");
        if (bodies.length > 0) {
            bodies = bodies[0];
            bodies.innerHTML = sFilling;
        }
        else {
            doc.open();
            doc.write(sFilling);
            doc.close();
        }
    }
}

function posProgressLayer(progressLayerId, relativeObjId, progressHeight, progressWidth) {
    var progressLayer = document.getElementById(progressLayerId);
    var relativeObj = null;

    if (relativeObjId != null && relativeObjId != '') relativeObj = document.getElementById(relativeObjId);
    if (!isExistingObj(relativeObj)) relativeObj = document.getElementsByTagName('BODY')[0];

    if (!progressLayer || !relativeObj) return;

    progressLayer.className = 'loadIndicator';
    var pos = findPos(relativeObj);
    var tp = pos.top;
    var lft = pos.left;
    var ht = relativeObj.clientHeight;
    var wh = document.body.clientWidth;
    tp = tp + (ht / 2) - (progressHeight / 2);
    lft = (wh / 2) - (progressWidth / 2) - lft;

    moveIt(progressLayer, tp, lft);
}

function moveIt(obj, mvTop, mvLeft) {
    obj.style.position = "absolute";
    obj.style.top = parseInt(mvTop) + 'px';
    obj.style.left = parseInt(mvLeft) + 'px';
}

function findPos(obj) {
    var curleft = curtop = 0;
    if (obj.offsetParent) {
        do {
            curleft += obj.offsetLeft;
            curtop += obj.offsetTop;
            obj = obj.offsetParent
        }
        while (obj);
    }

    return { left: curleft, top: curtop };
}


// Cross-browser implementation of element.addEventListener()
// Use: addListener(elem, "event name", func);
function jt_addListener(elem, evnt, func) {
    if (elem.addEventListener) // W3C DOM
        elem.addEventListener(evnt, func, false);
    else if (elem.attachEvent) { // IE DOM
        var r = elem.attachEvent("on" + evnt, func);
        return r;
    }
    else window.status('Failed to attach event.');
}


function isExistingObj(elem) { return (typeof elem !== 'undefined' && elem != null); }

function modifyLangLinks() {
    var chk = document.getElementById('chk');
    if (!isExistingObj(chk)) return;

    var param = "&chk=1";
    var checked = chk.checked;
    var reg = new RegExp(param, "ig");

    var anchors = document.getElementsByTagName('a');
    for (var c = 0; c < anchors.length; c++) {
        var anc = anchors[c];
        var href = anc.href;
        if (checked == true && href.indexOf(param) == -1) { href = href + param; } else if (checked == false && href.indexOf(param) > -1) { href = href.replace(reg, ''); }
        anc.href = href.replace(/&&/, '&');
    }
}

function imageButtons_AssignHandlers() {
    // add handlers
    for (var c = 0; c < imageButtons.length; c++) {
        var img = document.getElementById(imageButtons[c]);
        if (!isExistingObj(img))
            continue;

        jt_addListener(img, 'mouseover', function(imgObj) {
            return function() {
                var src = imgObj.src;
                if (!ImgSrc.testSuffixes(src)) {
                    src = ImgSrc.addSuffix(src, ImgSrc.suffixes['mouseon']);
                    imgObj.src = src;
                }
            }
        } (img));

        jt_addListener(img, 'mouseout', function(imgObj) {
            return function() {
                var src = imgObj.src;
                src = ImgSrc.remSuffix(src, ImgSrc.suffixes['mouseon']);
                imgObj.src = src;
            }
        } (img));
    }

    //preload images
    for (var c = 0; c < imageButtons.length; c++) {
        var img = document.getElementById(imageButtons[c]);
        if (!isExistingObj(img))
            continue;

        var src = img.src;
        if (ImgSrc.testSuffixes(src)) src = ImgSrc.remSuffix(src);
        src = ImgSrc.addSuffix(src, ImgSrc.suffixes['mouseon']);
        ImgSrc.preload(src);
    }
}

function reloadForm(oForm) {
    if (!isExistingObj(oForm)) { oForm = document.getElementsByTagName('FORM')[0]; }
    oForm.reset();

    var _reloadForm = false;
    var elements = oForm.elements;
    for (i = 0; i < elements.length; i++) {
        field_type = elements[i].type.toLowerCase();

        switch (field_type) {
            case "text":
            case "textarea":
                if (elements[i].value != "") _reloadForm = true;
                break;

            case "radio":
            case "checkbox":
                if (elements[i].checked == true) _reloadForm = true;
                break;

            case "select-one":
            case "select-multi":
                if (elements[i].selectedIndex > -1) _reloadForm = true;
                break;

            default:
                break;
        }

        if (_reloadForm) { window.location.reload(true); break; }
    }
}


function clearForm(oForm) {
    if (!isExistingObj(oForm)) { oForm = document.getElementsByTagName('FORM')[0]; }

    oForm.reset();
    //debugger
    var elements = oForm.elements;

    for (i = 0; i < elements.length; i++) {

        field_type = elements[i].type.toLowerCase();

        switch (field_type) {

            case "text":
            case "password":
            case "textarea":
            //case "hidden":

                elements[i].value = "";
                break;

            case "radio":
            case "checkbox":
                if (elements[i].checked == true) {
                    elements[i].setAttribute('checked', 'false');
                    elements[i].checked = false;
                }
                break;

            case "select-one":
            case "select-multi":
                elements[i].selectedIndex = -1;
                break;

            default:
                break;
        }
    }
}

if (typeof (Sys) !== "undefined") Sys.Application.notifyScriptLoaded();
