//this must exceed (or match) the maximum toggle time (specified within homepage script)
var maxToggleDuration = 500;
var urlPrefix = "http://www.shell.com/home/";
var do_it=true;
//arrays for remote rss/xml stored content
var newsDateRss = new Array();
var newsRss = new Array();

//init the effects
var forConsumers, forBusinesses, latestNews, sharePrice;

//left navigation expandable elements need to be defined in an array for auto-collapse feature
var left_navigation_auto_collapse = ["forConsumers","forBusinesses"];

//Rss retrieval
var xmlHttp;
var strHtml='';
var sharePricePrefix = 'http://www-static.shell.com/static/html/homepage/images/global/';

//share prices array for xml data
var sharesLatest = new Array();
var shareCityName = ['Amsterdam','London','New York'];
var sharePriceLoop = true;
var TimeoutID;

window.onload = function(){
    resize_grid();
    buildRssNews();
    switchSharePrices(0);
}


//reformats headers with "next" arrow and according link
function buildRssNews(){
    for(i=0; i<=newsItemsMax-1; i++){
        newsDate[i].innerHTML = newsDateRss[i] + "&nbsp;<a onclick=\"javascript:newsSwitch(" + (i+1) + ",'next')\" title=\"next\"><img id=\"next\" src=\"/static/html/homepage/images/panels/next.gif\"></a>";
        news[i].innerHTML = newsRss[i];
    }
}

//expands all 3 news items
function showAllNews(){
    var displayMode = objNewsTrigger.style.display;

    //if compressing, it's important to run the toggle before changing the display types of element containers
    //also, ensure display mode is triggered after the duration attribute of fx.Combo
    if(displayMode == "block"){
        objNewsTrigger.style.display = displayMode;

        //rebuild content in new format (for expanded mode)
        reformatLatestNews();
        latestNews.toggle();
        objnewshomepagePM.style.background='url("/static/html/homepage/images/panels/heading_split_minus.gif")';
    }
    else{
        latestNews.toggle();
        setTimeout("compressNews('"+displayMode+"')",(maxToggleDuration+1));
    }
}

//when in expanded mode, the news items "subItems" headings are customised visually
function reformatLatestNews(){
    //don't forget to remove the link to the "next" news item when viewed in this mode (function removeNewsSuffix())
//    newsDate[0].innerHTML = "1-" + newsItemsMax + " of " + newsItemsMax;
    newsDate[0].innerHTML = "&nbsp;";
    news[0].innerHTML = "<strong>" + removeNewsSuffix(newsDateRss[0]) + "</strong><br />" + newsRss[0] + "";

    for(i=1; i<=newsItemsMax-1; i++){    
        newsDate[i].style.display = "none";
        news[i].innerHTML = "<p><strong>" + removeNewsSuffix(newsDateRss[i]) + "</strong><br />" + newsRss[i] + "</p>";
    }
    objNewsTrigger.style.display = "none";

    news[newsItemsMax-1].innerHTML += '<br /><a href="/home/Framework?siteId=media-en" title="More news">More news</a>&nbsp;<img id="next" src="/static/html/homepage/images/panels/next.gif">';
}

//remove all text to the right hand side of the date, as it isn't needed in this view
function removeNewsSuffix(title){
    var positionStart = title.lastIndexOf("&nbsp;|&nbsp;");
    return title.substr(0,positionStart);
}

//reformat news data back to initial view-state
function compressNews(displayMode){
    objNewsTrigger.style.display = "block";

    //reset initial loading state
    newsDate[0].innerHTML = newsDateRss[0] + "&nbsp;<a href=\"javascript:newsSwitch(1,'next')\" title=\"next\"><img id=\"next\" src=\"/static/html/homepage/images/panels/next.gif\"></a>";
    news[0].innerHTML = newsRss[0];

    //toggle between plus and minus icon
    objnewshomepagePM.style.background='url("/static/html/homepage/images/panels/heading_split_plus.gif")';
}

//toggle between a news item, and the next news array item
function newsSwitch(id,mode){
    var toShow = 0;

    for(i=0; i<=newsItemsMax; i++){
        if(i == id){
            toShow = (mode == 'previous') ? i-1 : i+1;
            if (toShow < 1) { toShow = newsItemsMax; }
            break;
        }
    }

    if((toShow>0) && (toShow < (newsItemsMax+1) )){
        var element;
        var idNext;


        for(i=1; i<=newsItemsMax; i++){
            if(i==id){
                //show requested news item

                switch(mode){
                    case 'previous':
                        idNext = id - 1;
                        if (idNext < 1) { idNext = newsItemsMax; }
                        element = idNext - 1;
                        if (element < 0) { element = newsItemsMax - 1 ; }

                        //alert("id: "+id+" toShow: "+toShow+" element: "+element);
                        break;
                    case 'next':
                        element = id;
                        idNext = element + 1;
                        break;
                }

                //add innerHTML to compressed mode elements
                if(mode == 'next' && element == newsItemsMax-1)
                {
	                newsDate[0].innerHTML = newsDateRss[element];
                	news[0].innerHTML = newsRss[element];
								}
								else
								{
                	newsDate[0].innerHTML = newsDateRss[element] + "&nbsp;<a href=\"javascript:newsSwitch(" + (idNext) + ",'next')\" title=\"next\"><img id=\"next\" src=\"/static/html/homepage/images/panels/next.gif\"></a>";
  	              news[0].innerHTML = newsRss[element];
								}
							
            }
        }
    }
    else{
        if(mode == 'next'){
            //reset to first news item
            newsDate[0].innerHTML = newsDateRss[0] + "&nbsp;<a href=\"javascript:newsSwitch(1,'next')\" title=\"next\"><img id=\"next\" src=\"/static/html/homepage/images/panels/next.gif\"></a>";
            news[0].innerHTML = newsRss[0];
        }
    }
}

//change plus to minus and vice versa (this function is not context based)
function togglePlusMinus(idElement,style){
    //style should be defined as one of the following:
    //> leftnav
    //> panel (right-hand)

    toSwitch = "obj" + idElement.toLowerCase() + "PM";
    objSwitch = eval(toSwitch);

    var suffix = "";
    var image_style = "";

    switch(style){
        case "leftnav":
            image_style = "_small";
            break;
        case "panel":
            image_style = "";
            break;
    }

    //need to assign background style for runtime manipulation
    if(objSwitch.style.backgroundImage.length == 0){
        objSwitch.style.backgroundImage = 'url("/static/html/homepage/images/panels/heading_split_plus' + image_style + '.gif")';
    }

    suffix = (objSwitch.style.backgroundImage.indexOf("_plus") > -1) ? "_minus" : "_plus";
    objSwitch.style.backgroundImage = 'url("/static/html/homepage/images/panels/heading_split' + suffix + image_style + '.gif")';

    //turn off share price loop if expanding the share price module
    if((idElement == "sharePrice") && (suffix == "_minus")){
        sharePriceLoop = false;
        clearTimeout(TimeoutID);
        switchSharePrices(0);
        do_it=false;
    }
    else if((idElement == "sharePrice") && (suffix == "_plus")){
        sharePriceLoop = true;
        do_it=true;

        //reset to first city
        switchSharePrices(0);
    }
}

//automatically triggers scrolling between share price items
function switchSharePrices(elementPosition){
     var startPos = (elementPosition == 0) ? 0 : parseInt(elementPosition) * 4;
    var offset = elementPosition;
    if(do_it)
    {

    objShareCityName.innerHTML = shareCityName[elementPosition];

    //when last share is displayed, force the first share item to reload (and subsequently loop)
    if(offset == 2){
        offset = 0;
    }
    else{
        offset++;
    }
	
    //only run loop if boolean allows
        if(sharePriceLoop){
            TimeoutID=setTimeout("switchSharePrices(" + offset + ")",3000);
        }
        else{
            if(!elementPosition == 0){
                setTimeout("switchSharePrices(0)",0);
            }
        }

    if(elementPosition == 2){
        objShareHeadingA.innerHTML = "RDS.A";
        objShareHeadingB.innerHTML = "RDS.B";
    }
    else{
        objShareHeadingA.innerHTML = "RDSA";
        objShareHeadingB.innerHTML = "RDSB";
    }

    objRdsa.innerHTML = sharesLatest[startPos];
    objRdsb.innerHTML = sharesLatest[startPos+1];
    objImgRdsa.src = sharesLatest[startPos+2];
    objImgRdsb.src = sharesLatest[startPos+3];
    }

}

//assignment of an element to object for easy js processing
function getElement(id){
    return document.getElementById(id);
}

//required browser sniffer for XmlHttp() Rss retrieval
function browserSniffer(){
    browserAgent = navigator.userAgent.toLowerCase();
    isMajor = parseInt(navigator.appVersion);

    isInternetExplorer = (browserAgent.indexOf("msie") != -1);
    isInternetExplorer7 = (isInternetExplorer && (isMajor == 4) && (browserAgent.indexOf("msie 7.")!=-1));

    isWindows = ((browserAgent.indexOf("win")!=-1) || (browserAgent.indexOf("16bit")!=-1));
}

//calculate whether an up or down arrow should be displayed for live share prices being viewed
function sharePriceUpDown(value){
    var price = value.substr(0,1);
    returnPrice='';
    if(price == '-')
    {
        returnPrice = 'shares_down.gif';
    }
    else if(value > 0)
    {
        returnPrice = 'shares_up.gif';
    }
    else
    {
        returnPrice = 'shares_even.gif';
    }
    return sharePricePrefix + returnPrice;
}

//called from flash movie.
//it loads the non-alternative flash image into the flash div if FlashhExpress installation was unsuccessful for any reason
function hideFlash(siteLocation){
    obj = getElement("flashcontent");
    obj.innerHTML = '<img src="flash/noflash_alternatives/' + siteLocation.toLowerCase() + '.jpg">';
}

//ensure only 1 item in the left navigation bar is only expanded at once
function toggleLeftNav(obj,plusMinusGridPos){
    var objInternal;
    var toSwitch;

    for(i=0; i<=left_navigation_auto_collapse.length-1; i++){
        toSwitch = "obj" + left_navigation_auto_collapse[i].toLowerCase() + "PM";

        if(left_navigation_auto_collapse[i] == obj){
            obj = eval(toSwitch).style;

            if(obj.backgroundImage.length == 0){
                obj.backgroundImage = 'url("/static/html/homepage/images/panels/heading_split_plus_small.gif")';
            }

            obj.backgroundImage = (obj.backgroundImage.indexOf("_plus") > -1) ? 'url("/static/html/homepage/images/panels/heading_split_minus_small.gif")' : 'url("/static/html/homepage/images/panels/heading_split_plus_small.gif")';
            eval(left_navigation_auto_collapse[i]).toggle();
        }
        else{
            //to ensure the 2 left hand navigation items are not both expanded at once, uncomment these 2 lines
            //eval(toSwitch).style.backgroundImage = 'url("images/panels/heading_split_plus_small.gif")';
            //eval(left_navigation_auto_collapse[i]).hide();
        }
    }
}

//resize both the header and the footer
function resize_grid(){
    var window_width = (navigator.appName.indexOf("Microsoft")!=-1) ? document.body.offsetWidth : window.outerWidth;
    var initial_size = (navigator.appName.indexOf("Microsoft")!=-1) ? "900px" : "990px";
    var reduction = (navigator.appName.indexOf("Microsoft")!=-1) ? 40 : 40;
    var obj_header = getElement("headerWrapper");
    var obj_footer = getElement("footerWrapper");

    if(obj_header.style.width.length == 0){obj_header.style.width = "1024px";}
    if(obj_footer.style.width.length == 0){obj_footer.style.width = "1024px";}

    var str = "";

    if(window_width > 1024){
        obj_header.style.width = initial_size;
        obj_footer.style.width = initial_size;
    }
    else if((window_width > 800) && (window_width < 1024)){
        obj_header.style.width = "" + (window_width-reduction) + "px";
        obj_footer.style.width = "" + (window_width-reduction) + "px";
    }
    else{
        if(navigator.appName.indexOf("Microsoft")!=-1){
            obj_header.style.width = "770px";
            obj_footer.style.width = "770px";
        }
        else{
            obj_header.style.width = "800px";
            obj_footer.style.width = "800px";
        }
    }

    //for debug purposes (ie only)
    //str += "window width: " + window_width + "\n";
    //str += "header width: " + obj_header.style.width + "\n";
    //str += "footer width: " + obj_footer.style.width;
    //window.status = str;
}