var EN = { modules:[] };

if(Array.prototype.push == null) { Array.prototype.push = function(){ for(var i = 0; i < arguments.length; i++){ this[this.length] = arguments[i]; }; return this.length; };};
if(String.prototype.trim == null){ String.prototype.trim = function() { return this.replace(/^\s+|\s+$/, ''); }; };

EN.browserLang = String(navigator.language ? navigator.language : navigator.userLanguage).toLowerCase().replace(/-[a-z]+$/, "") || "en";

EN.registerModule = function(mod, obj) {
        if(mod in EN.modules) {
                return;
        };
        EN.modules[mod] = true;
        EN[mod] = obj;
};

EN.moduleEvent = function(eventType) {
        for(mod in EN.modules) {
                if((eventType in EN[mod]) && typeof(EN[mod][eventType]) == "function") {
                        try {
                                EN[mod][eventType]();
                        } catch (err) {};
                };
        };
};

EN.onDomReady = function() {
        var ignoreMe = document.body.offsetWidth;
        EN.moduleEvent("onDomReady");
};

EN.onLoad = function() {
        EN.moduleEvent("onLoad");
};

EN.onUnload = function() {
        EN.moduleEvent("onUnload");
};

EN.onResize = function() {
        EN.moduleEvent("onResize");
};

EN.addEvent = (window.addEventListener) ? function(obj, evType, fn, useCapture){
        obj.addEventListener(evType, fn, useCapture || true);
        return true;
} : function(obj, evType, fn, useCapture){
        var r = obj.attachEvent("on"+evType, fn);
        return r;
};

EN.removeEvent = (window.addEventListener) ? function(obj, evType, fn, useCapture){
        obj.removeEventListener(evType, fn, useCapture || true);
        return true;
} : function(obj, evType, fn, useCapture) {
        try {
                var r = obj.detachEvent("on"+evType, fn);
                return r;
        } catch(err) { return false; };
};

EN.addEvent(window, "load",   EN.onLoad);
EN.addEvent(window, "unload", EN.onUnload);
EN.addEvent(window, "resize", EN.onResize);

EN.stopEvent = function(e) {
        e = e || document.parentWindow.event;
        if (e.stopPropagation) {
                e.stopPropagation();
                e.preventDefault();
        };
        
        /*@cc_on@*/
        /*@if(@_win32)
        e.cancelBubble = true;
        e.returnValue  = false;
        /*@end@*/
        return false;
};

EN.hasClass = function(e, c) {
        return new RegExp("(^|\\s)" + c + "(\\s|$)").test(e.className);
};

EN.addClass = function(e,c) {
        if(new RegExp("(^|\\s)" + c + "(\\s|$)").test(e.className)) { return; };
        e.className += ( e.className ? " " : "" ) + c;
};

EN.removeClass = function(e,c) {
        e.className = !c ? "" : e.className.replace(new RegExp("(^|\\s*\\b[^-])"+c+"($|\\b(?=[^-]))", "g"), "");
};

EN.getInnerText = function(el) {
        if (typeof el == "string" || typeof el == "undefined") return el;
        if(el.innerText) return el.innerText;

        var txt = '', i;
        for (i = el.firstChild; i; i = i.nextSibling) {
                if (i.nodeType == 3) { txt += i.nodeValue; }
                else if (i.nodeType == 1) { txt += fd.getInnerText(i); };
        };
        return txt;
};

EN.joinNodeLists = function() {
        if(!arguments.length) { return []; };
        var nodeList = [];
        for (var i = 0; i < arguments.length; i++) {
                for (var j = 0, item; item = arguments[i][j]; j++) {
                        nodeList[nodeList.length] = item;
                };
        };
        return nodeList;
};

EN.registerModule("comingUp", {
        tableData:[],
        max:0,
        current:0,
        loadHour:new Date().getHours(),
        interval:null,

        onDomReady:function() {         
                var tbl = document.getElementById("coming-up");
                if(!tbl) { return; };
                EN.comingUp.max = tbl.rows.length;
                var tds, time;
                for(var i = 0, row; row = tbl.rows[i]; i++) {
                        tds = row.cells;
                        if(!tds.length) { continue; };
                        time = EN.getInnerText(tds[tds.length - 1]).replace(/[^\d]/, "");
                        EN.comingUp.tableData.push([time, row]);
                };
                EN.comingUp.pause();
        },
        pause:function() {
                if(EN.comingUp.tableData.length) {
                        var secs = 60 - new Date().getSeconds();
                        if(EN.comingUp.tableData[EN.comingUp.current][0] < new Date().getMinutes()) {
                                secs = (60 - new Date().getMinutes()) * 60;
                                if(EN.comingUp.tableData[EN.comingUp.current][0] > 0) {
                                        secs += EN.comingUp.tableData[EN.comingUp.current][0] * 60;
                                };
                        } else if(EN.comingUp.tableData[EN.comingUp.current][0] > new Date().getMinutes()) {
                                secs = (EN.comingUp.tableData[EN.comingUp.current][0] - new Date().getMinutes()) * 60;
                        };
                        secs -= 60 - new Date().getSeconds();
                        setTimeout(EN.comingUp.fade, Math.floor(secs * 1000));
               };
        },
        fade:function() {
                var rowToFade = EN.comingUp.tableData[EN.comingUp.current];
                EN.comingUp.current++;
                var rowToHighlight = EN.comingUp.tableData.length - 1 > EN.comingUp.current ? EN.comingUp.tableData[EN.comingUp.current] : false;

                if(rowToFade) {
                        EN.removeClass(rowToFade[1], "next-program");
                        $(rowToFade[1]).animate({opacity: 0.5}, 2000);
                };
                
                if(rowToHighlight) {
                        EN.addClass(rowToHighlight[1], "next-program");
                        EN.comingUp.pause();
                } else {
                        setTimeout(EN.comingUp.fade, 60000);
                };
        }
});

EN.registerModule("relatedStories", {
        stories:[],
        offset:0,

        onDomReady:function() {
                var rsb = document.getElementById("related-stories");
                if(!rsb || !(rsb.className.search("wires") == -1)) { return; };

                try {                         
                        var ul      = rsb.getElementsByTagName("ul")[0],
                            stories = ul.getElementsByTagName("li");
                } catch(err) {
                        return;
                };
                
                if(!stories || stories.length < 6) {                        
                        return; 
                };
                
                // Remove the class that rounds the bottom corners etc
                rsb.className = rsb.className.replace("no-scroll-buttons", "");
                
                $(ul).before('<div id="rs-up-wrap" class="disabledButton"><a id="rs-up" href="#related-stories">' + EN.pageTranslations.getTranslation('previous-stories') + '</a></div>').after('<div id="rs-down-wrap"><div><a id="rs-down" href="#related-stories">' + EN.pageTranslations.getTranslation('next-stories') + '</a></div></div>');
                $("#rs-up").click(EN.relatedStories.scroll);
                $("#rs-down").click(EN.relatedStories.scroll);
                
                for(var i = 5, li; li = stories[i]; i++) {
                        li.className = "hide";
                };

                EN.relatedStories.stories = stories;
        },
        scroll:function() {
                if(this.id == "rs-down") {
                        if(!(EN.relatedStories.offset + 1 < EN.relatedStories.stories.length - 4)) {
                                return false;
                        };
                        EN.relatedStories.offset++;
                } else {
                        if(!(EN.relatedStories.offset - 1 > -1)) {
                                return false;
                        };
                        EN.relatedStories.offset--;
                };
                
                for(var i = 0, li; li = EN.relatedStories.stories[i]; i++) {
                        li.className = i < EN.relatedStories.offset || i > EN.relatedStories.offset + 4 ? "hide" : "";
                };
                
                EN.relatedStories.showHideButtons();
                
                try { this.blur(); } catch(err) {};
                
                return false;
        },
        showHideButtons:function() {
                if(EN.relatedStories.offset == 0) {
                        $("#rs-up-wrap").addClass("disabledButton");
                } else {
                        $("#rs-up-wrap").removeClass("disabledButton");
                };
                
                if(EN.relatedStories.offset == EN.relatedStories.stories.length - 5) {
                        $("#rs-down-wrap").addClass("disabledButton");
                } else {
                        $("#rs-down-wrap").removeClass("disabledButton");
                };
        }
});

EN.registerModule("textTools", {
        initialSize:1,
        textSize:1,         
        onDomReady:function() {                
                var at = $("#article-text");
                
                if(!at || at.hasClass("norelated")) { return; };
                
                EN.textTools.initialSize = (("lang" in EN) && EN.lang == "ar") ? 4 : 1;
                
                EN.textTools.textSize = EN.textTools.initialSize;
                
                $(at).prepend('<ol id="article-tools"><li><a id="txt-smaller" href="#article-tools">'+EN.pageTranslations.getTranslation('smaller_text')+'</a></li><li><a id="txt-larger" href="#article-tools">' + EN.pageTranslations.getTranslation('larger_text') + '</a></li><li><a id="print-page" href="#article-tools">' + EN.pageTranslations.getTranslation('print_article') + '</a></li></ol>');
                $("#article-tools a").each(function() { $(this).click( EN.textTools.toolAction ); });
                
                var ts = EN.cookie.readCookie("EN_textSize");
                if(ts) {                           
                        EN.textTools.textSize = Number(ts) < EN.textTools.initialSize ? EN.textTools.initialSize : ts;
                };
                
                EN.textTools.resizeText();
        },
        toolAction:function(e) {
                if(this.id.search(/-larger/) != -1) {
                        if(EN.textTools.textSize > 20) return false;
                        EN.textTools.textSize++;
                        EN.textTools.resizeText();
                } else if(this.id.search(/-smaller/) != -1) {
                        if(EN.textTools.textSize < EN.textTools.initialSize+1) return false;
                        EN.textTools.textSize--;
                        EN.textTools.resizeText();
                } else {
                        try { window.focus(); } catch(err) {};
                        window.print();
                };
                
                return EN.stopEvent(e);
        },
        resizeText:function() {
                EN.cookie.createCookie("EN_textSize", EN.textTools.textSize);
                $("#article-text").css("fontSize", (100 + ((EN.textTools.textSize - 1) * 10)) + "%");
        }
});

EN.registerModule("centerArticleTitle", {
        onDomReady:function() {                
                var titleWrap = document.getElementById("title-wrap"),
                    player    = document.getElementById("player");               
                            
                if(!titleWrap) { return; };   
                
                var h1           = titleWrap.getElementsByTagName("h1")[0],               
                    a            = h1.getElementsByTagName('a')[0]; 
                    
                if(a && a.offsetWidth > h1.offsetWidth) {
                        var c = { "small" : "smaller", "smaller" : "smallest" };
                        if(a.className in c) {
                                a.className = c[a.className];
                        };
                }; 
                
                titleWrap.style.marginTop = Math.max(0, Math.floor((titleWrap.parentNode.offsetHeight - titleWrap.offsetHeight) / 2)) + "px";
        }
});

EN.registerModule("videoPlayer", {
        onDomReady:function() {                               
                var pl = document.getElementById("article-player");
                              
                if(!pl) { return; };  
                
                var lnk = document.createElement('a'),
                    txt;
                
                try {
                        txt = EN.pageTranslations.getTranslation('play_pause_video');
                } catch(e) {
                        txt = "Play/Pause Video";
                };
                
                lnk.appendChild(document.createTextNode(txt));
                lnk.href = "#article-player";
                
                lnk.onclick = function(e) {
                        var pl = document.getElementById("article-player");  
                        if(pl && pl.tagName && pl.tagName.search(/object|embed/i) != -1) {                         
                                try { pl.playExt(); } catch(err) { }; 
                        };                    
                        return EN.stopEvent(e);
                };
                
                lnk.id = "play-pause";
                                               
                pl.parentNode.appendChild(lnk);               
        }
});

EN.registerModule("externalLinks", {
        onDomReady:function() {
                var links = document.getElementsByTagName("a");
                for(var i = 0, link; link = links[i]; i++) {
                        try {
                                if(link.getAttribute("href") && String(link.getAttribute("rel")).search("external") != -1) {
                                        link.onclick = EN.externalLinks.openWin;                                 
                                };
                        } catch(err) { };
                };
        },
        openWin:function(e) { 
                e = e || window.event;
                
                if (e.shiftKey || e.altKey || e.ctrlKey || e.metaKey) return true;

                var oWin = window.open(this.getAttribute('href'), '_blank');
                if (oWin) {
                        if (oWin.focus) oWin.focus();
                        return false;
                }
                oWin = null;
                return true;
        } 
});

EN.registerModule("currentTime", {
        timer:null,
        clock:null,
        onDomReady:function() {                
                EN.currentTime.clock = document.getElementById("current-time");
                if(!EN.currentTime.clock) { return; };                 
                EN.currentTime.setClock();
                EN.currentTime.timer = setInterval("EN.currentTime.setClock()", 30000);                
        },
        setClock:function() {                         
                var timeStamp = new Date().getMinutes();
                if(timeStamp < 10) timeStamp = "0" + String(timeStamp);                
                EN.currentTime.clock.innerHTML = ": " + timeStamp;
        },
        onUnload:function() {
                clearInterval(EN.currentTime.timer);
                EN.currentTime.timer = null;
        }
});

EN.registerModule("navigation", {  
        complete:false,                 
        onDomReady:function() {
                if(!EN.navigation.complete) { EN.navigation.init(); };              
        },
        init:function() { 
                EN.navigation.complete = true; 
                EN.navigation.languageNavigation();              
                EN.navigation.space("#languageNav");
                EN.navigation.space("#categoryNav");
                EN.navigation.repositionSubcategories();                
        },
        space:function(id) {         
                var totalW = 0,
                    cnt    = 0,
                    olW    = $(id).width();                    
                $(id + " > li").each(function() { cnt++; totalW += this.offsetWidth; });                 
                totalW -= (cnt - 2) * 8;                 
                var empty   = olW - totalW,
                    pdSpace = Math.max(1, Math.floor(empty / (cnt - 1))),
                    bgSpace = Math.max(0, pdSpace - 8);                 
                $(id + " > li:gt(0)").each(function() { $(this).css("paddingLeft", pdSpace + "px"); $(this).css("backgroundPosition", bgSpace + "px 0px"); $("a:first", this).each(function() { $(this).css("paddingLeft", "0px"); }); });
        },         
        repositionSubcategories:function() {
                var ols = document.getElementById("categoryNav").getElementsByTagName('ol'),
                    totalW, olW, liPos, li, nudge;
                    
                for(var i = 0, ol; ol = ols[i]; i++) {
                        totalW = liPos = 0;                              
                        $("li", ol).each(function() { totalW += this.offsetWidth; });
                        li = ol.parentNode;
                        if(li.tagName) liPos += li.offsetWidth;
                        while(li.previousSibling) {
                                li = li.previousSibling;
                                if(li.tagName) liPos += li.offsetWidth;
                        };                        
                        nudge = Math.max(0, Math.floor(liPos - totalW) - 8);
                        $("li:first", ol).css("paddingLeft",nudge + "px");
                };                  
        },
        languageNavigation:function() {
                if(!EN.cookie.cookieEnabled()) { return; };                 
                $("#languageNav a").each(function() { $(this).click(function(e) {EN.cookie.createCookie("EN_lang", this.lang, 365); }) });               
        }
});

EN.registerModule("cookie", {
        enabled:null,
        cookieEnabled: function() {
                if(EN.cookie.enabled != null) return EN.cookie.enabled;
                var cookieEnabled = (navigator.cookieEnabled) ? true : false;
                if (typeof navigator.cookieEnabled == "undefined" && !cookieEnabled) {
                        document.cookie="testcookie";
                        cookieEnabled=(document.cookie=="testcookie")? true : false;
                        document.cookie="";
                };
                EN.cookie.enabled = cookieEnabled;
                return cookieEnabled;
        },
        createCookie:function(name,value,days) {
                if (days) {
                        var date = new Date();
                        date.setTime(date.getTime()+(days*24*60*60*1000));
                        var expires = "; expires="+date.toGMTString();
                } else { expires = ""; };
                document.cookie = name+"="+value+expires+"; path=/; domain=euronews.net";
        },
        readCookie:function(name) {
                var nameEQ = name + "=";
                var ca = document.cookie.split(';');
                for(var i=0;i < ca.length;i++) {
                        var c = ca[i];
                        while(c.charAt(0)==' ') { c = c.substring(1,c.length); };
                        if (c.indexOf(nameEQ) == 0) { return c.substring(nameEQ.length,c.length); };
                };
                return null;
        }
});

EN.registerModule("addStyleSheet", {
        filesAdded:[],
        addFile:function(filename) {                  
                if(filename in EN.addStyleSheet.filesAdded) { return; };                
                var fileref = document.createElement("link");
                fileref.setAttribute("rel", "stylesheet");
                fileref.setAttribute("type", "text/css");
                fileref.setAttribute("href", filename);                 
                if (typeof fileref!="undefined") { document.getElementsByTagName("head")[0].appendChild(fileref) };
                fileRef = null;          
        }
});

EN.registerModule("warningiphone",{
                onDomReady:function() {
                var ua = navigator.userAgent ; 
                var sd = "Blackberry,Blazer,Handspring,iPhone,iPod,Kyocera,LG,Motorola,Nokia,Palm,Portable,Samsung,Smartphone,SonyEricsson,Symbian,WAP";
                var ad=sd.split(",");
                var notice = 'Visit our  optimized site for <a href="http://m.euronews.net"><b>iPhone and Blackberry at http://m.euronews.net</b></a>';
                for (var i=0; i<ad.length; i++) {
                        if(ua.indexOf(ad[i])!= -1){
                             var promo = document.getElementById('videoBar') ; 
                             if(promo != null) {
                                        var divs = promo.getElementsByTagName('DIV') ;
                                        if(divs != null){ 
                                                var mydiv = divs[0] ; 
                                                mydiv.innerHTML  = notice ;      
                                                mydiv.style.fontSize = "32px";
                                        }                   
                             }       
                             return false;
                        }
                }
                
        
                         
        }



});

