/* START Weather functions */
/* ======================= */

/* Associative Array for mapping Cities and their synop number.*/
var citySynopNoMap = { "Alexander Bay":68403, "Aliwal North":68546, "Alldays":68171, "Badplaas":99991, "Beaufort West":68727, "Bela Bela":68268, "Bethlehem":68461, "Bhisho":68752, "Bloemfontein":68443, "Calvinia":68618, "Cape Agulhas":68920, "Cape Point":68916, "Cape St. Francis":68939, "Cape Town":68819, "Clan William":68711, "Cradock":68744, "De Aar":68538, "Durban":68588, "East London":68858, "Ermelo":68267, "Excelsior":68719, "Fauresmith":68541, "Ficksburg":68449, "Fort Beaufort":68747, "Geelbek":68811, "George":68828, "Giants Castle":68589, "Graaff-Reinet":68737, "Grabouw":68925, "Graskop":68287, "Groblersdal":99992, "Hermanus":68918, "Ixopo":68575, "Johannesburg":68361, "Joubertina":68833, "Kimberley":68438, "Klerksdorp":68347, "Kokstad":68577, "Komatidraai":68297, "Kroonstad":68355, "Kuruman":68333, "Ladysmith":68479, "Lephalale":68155, "Lydenburg":68185, "Mafikeng":68242, "Malmesbury":68715, "Margate":68591, "Molteno":688191, "Mooriver":68485, "Mossel Bay":68928, "Mthatha":68668, "Musina":68180, "Nelspruit":68289, "Newcastle":68377, "Ngqura (Coega)":68837, "Oudtshoorn":68827, "Paarl":68713, "Phalaborwa":68191, "Piet Retief":68385, "Pietermaritzburg":68581, "Plettenberg Bay":68931, "Polokwane":68174, "Port Alfred":68843, "Port Elizabeth":68842, "Port St. Johns":68674, "Postmasburg":68429, "Potchefstroom":68350, "Pretoria":68262, "Queenstown":68647, "Redelinghuys":68710, "Richards Bay":68495, "Riversdale":68926, "Robertson":68718, "Rustenburg":68255, "Skukuza":68296, "Slangkop":68912, "Springbok":68512, "St. Lucia Estuary":68492, "Standerton":68372, "Stilbaai":68927, "Strand":68911, "Sutherland":68722, "Taung":68335, "Thabazimbi":68253, "Thohoyandou":68183, "Tzaneen":68188, "Uitenhage":68839, "Ulundi":68493, "Underberg":68572, "Upington":68424, "Van Reenen":68471, "Vereeniging":68353, "Vredendal":68614, "Vryburg":68338, "Vryheid":68387, "Welkom":68345, "Witbank":68273, "Worcester":68821, "NO_NAME":00000 }
var DEFAULT_SYNOP_NUMBER = 68361; // Johannesburg;
var currentWeatherButtonId = '#buttonJohannesburg';

/* Header weather data function call */
$(function(){loadWeatherHeader()});
/* Body weather data function call (only fetches this data if container <div> weatherContent exists)*/
$(function(){if($('#weatherContent').length > 0) loadWeatherBody()});
/* Header weather data function */
function loadWeatherHeader()
{
    var userCity = $('#userCity').val();
    $.get('/XmlHttpProxy/fetch?synopNumber='+getSynopNumber(userCity)+'&section=header&format=xml',null,function(data){$('#weatherContainer').html(data);},'text');
}

/* Loads weather page data */
function loadWeatherBody()
{
    var userCity = $('#userCity').val();
    var whichButtonId = "#button"+$.trim(userCity.replace(/ /g,''));
    $.get('/XmlHttpProxy/fetch?synopNumber='+getSynopNumber(userCity)+'&section=body&format=xml',null,function(data){$('#weatherContent').html(data);},'text')
    if($(whichButtonId))
    {
        $(currentWeatherButtonId).removeClass("selected");
        $(whichButtonId).addClass("selected");
        currentWeatherButtonId = whichButtonId;
    }
}


/* Load the inform topics bar if the article id exists */
$(function(){
    if (arrInformArray.length > 0)
    {
        for(var i = 0; i < arrInformArray.length; i++)
        {
   
            if (arrInformArray[i].InformFunction =='printSearchWebResults'|| arrInformArray[i].InformFunction =='printRelatedSearchResults') {
                loadInform(arrInformArray[i].SectionDiv,arrInformArray[i].InformFunction,arrInformArray[i].SectionName)
            }else if(arrInformArray[i].InformFunction =='printTopicsHeader'){
                loadInform(arrInformArray[i].SectionDiv,arrInformArray[i].InformFunction,"all")
            }
            else {
                loadInformArticle(arrInformArray[i].SectionDiv,arrInformArray[i].InformFunction,arrInformArray[i].SectionName)
            }

        }
    }
    
}
);
function loadInformArticle(container,functionType,articleID)
{
    if(functionType=="statistics"){
      $.get('/XmlHttpProxy/fetch?function='+functionType,null,function(data){$(container).html(data);},'text');
    }else{
      $.get('/XmlHttpProxy/fetch?function='+functionType+'&articleID='+articleID,null,function(data){$(container).html(data);},'text');
    }
    
}
function loadInform(container,functionType,subject)
{
    $.get('/XmlHttpProxy/fetch?function='+functionType+'&subject='+subject,null,function(data){ $(container).html(data);},'text');
}



/*
 * Convenience method for retrieving the synop number for a given city. Defaults to Johannesburg if the city cannot be found in the
 * global citySynopNoMap Associative Array.
 * */
function getSynopNumber(userCity)
{
    var synopNumber = citySynopNoMap[userCity];

    if(synopNumber)
        return synopNumber;
    else
        return DEFAULT_SYNOP_NUMBER; // Default to Johannesburg
}

/* Weather page <select/> function. Reloads the displayed 5 day forecast depending on the selected value. Return
 * false to prevent the form containing the <select/> tag submitting. */
function changeCity()
{
    // The synop number that was selected from the <select/> tag.
    var synopNumber = $('#synopNumberList').val();

    // The selected city name
    var whichCity = $('#synopNumberList option:selected').text()

    // id for which button was displayed last
    var whichButtonId = "#button"+$.trim(whichCity.replace(/ /g,''));
    
    // HTML to chunk to display busy/loading animation.
//    var busyHTML = "<div style='height:260px;'><div style='position:relative;top:130px;left:400px;'><img src='/timeslive/template/html_v1-0/img/icons/busy/remembermilk_orange.gif' align='left'>&nbsp;Loading 5 day forecast...</div></div></div>";

    $(currentWeatherButtonId).removeClass("selected");

    if($(whichButtonId))
    {
        $(whichButtonId).addClass("selected");
        currentWeatherButtonId = whichButtonId;
    }

//    $('#weatherContent').html(busyHTML);
    $.get('/XmlHttpProxy/fetch?synopNumber='+synopNumber+'&section=body&format=xml',null,function(data){$('#weatherContent').html(data);},'TEXT');
    
    return false;
}
/**
 *AJAX method to reload the 5 day weather from the <select/> element on the page. Also sets the buttons
 *above the 5 day display to match the select city.
 */
function viewCity(cityName)
{
    var whichButtonId = "#button"+$.trim(cityName.replace(/ /g,''));
    $.get('/XmlHttpProxy/fetch?synopNumber='+getSynopNumber(cityName)+'&section=body&format=xml',null,function(data){$('#weatherContent').html(data);},'TEXT');
    if($(whichButtonId))
    {
        $(currentWeatherButtonId).removeClass("selected");
        $(whichButtonId).addClass("selected");
        currentWeatherButtonId = whichButtonId;
    }
}

/* Jumps to the weather page.*/
function goToWeather()
{
    var newPath="";
    var hostName = window.location.host;


    // Check to see which host we're on and set the new path accordingly
    if(hostName.indexOf("ece-dev")!=-1 || hostName.indexOf("test")!=-1)
        newPath = window.location.protocol + "//" + window.location.host + '/timeslive/?filter=weather';
    else
        newPath = window.location.protocol + "//" + window.location.host + '/?filter=weather';
    
    window.location.href = newPath;
}
/* ===================== */
/* END Weather functions */


/* START Financial data functions */
/* ============================== */
/* Load topics header financial data */
$(function(){$.get('/XmlHttpProxy/fetch?inet=ZRUSM,J203&section=header&format=xml',null,function(data){$('#marketsContainer').html(data);},'text')});

/* Load Inet financial data */
$(function(){if($('#inetContainer').length > 0) $.get('/XmlHttpProxy/fetch?inet=GOLDM,PLATM,BRSPOT,ZRUSM,GPZRM,ERZRM,ZRJYM,J203&section=body&format=xml',null,function(data){$('#inetContainer').html(data);},'text')});
    
/* Load Business page financial data */
$(function() 
    {
        if($('#inetBPContainer').length > 0)
        {
            $.get('/XmlHttpProxy/fetch?inet=J200/J201/J202/J203/J210/J211/J212/J232/J150&section=businessPage|JSETODAY&format=xml',null,function(data){$('#bp_JSEtoday').html(data);},'TEXT');
            $.get('/XmlHttpProxy/fetch?inet=EURZAR/GBPZAR/USDZAR/JPYZAR&section=businessPage|CURRENCIES&format=xml',null,function(data){$('#bp_currencies').html(data);},'TEXT');
            $.get('/XmlHttpProxy/fetch?inet=GOLDM/PLATM/BRFUT&section=businessPage|COMMODITIES&format=xml',null,function(data){$('#bp_commodities').html(data);},'TEXT');
        }

    }
 );

/* Gets a quote for a given symbol. */
function getQuickQuote(inputElementId,trElementId)
{
    var symbol = $(inputElementId).val();

    if(symbol)
    {
        $.ajax({
            type: "GET",
            url: '/XmlHttpProxy/fetch',
            data: { inet:symbol, section:'quick', format:'xml' },
            contentType: "application/text; charset=utf-8",
            dataType: "text",
            error: function(xhr, desc, exceptionobj)
                   {
                    $(trElementId).html("<td colspan='4'>Connection error.</td>");
                   },
            success: function(inData)
                     {
                        if(inData.length>0)
                            $(trElementId).html(inData);
                        else
                            $(trElementId).html("<td colspan='4'>Share not found.</td>");
                     }

        });
        $(trElementId).css("visibility","visible");
    }
    else
    {
        $(trElementId).html("<td colspan='4'>Enter share symbol below.</td>");
        $(trElementId).css("visibility","visible");
    }
}

function goToBusiness()
{
    var newPath="";
    var hostName = window.location.host;


    // Check to see which host we're on and set the new path accordingly
    if(hostName.indexOf("ece-dev")!=-1 || hostName.indexOf("test")!=-1)
        newPath = window.location.protocol + "//" + window.location.host + '/timeslive/business';
    else
        newPath = window.location.protocol + "//" + window.location.host + '/business';

    window.location.href = newPath;
}
/* ============================ */
/* END Financial data functions */

/* START Career Junction API implementation*/
/*=========================================*/
$(function(){if($('#displayJob').length > 0) loadJob()});

function goToJobSearch()
{
    var newPath="";
    var hostName = window.location.host;


    // Check to see which host we're on and set the new path accordingly
    if(hostName.indexOf("ece-dev")!=-1 || hostName.indexOf("test")!=-1)
        newPath = window.location.protocol + "//" + window.location.host + '/timeslive/?filter=jobs';
    else
        newPath = window.location.protocol + "//" + window.location.host + '/?filter=jobs';

    window.location.href = newPath;
}

function goToJob()
{
    var jobAdNo = $.trim($('#jobNoInput').val());
    
    if(jobAdNo.length > 0)
    {
        var jobCode;

        jobAdNo = jobAdNo.toUpperCase();

        if(jobAdNo.indexOf("CJ")==0)
            jobCode = jobAdNo.split("J")[1];
        else
            jobCode = jobAdNo;

        window.location.href = '?filter=carjun&adNo='+jobCode;
    }
    
}

function gotToJobCJ(jobAdNo)
{
    var cjHref = 'http://www.careerjunction.co.za/car/job/appfrm.asp?adno='+jobAdNo;
    window.open(cjHref,'cjWindow','width=800,height=640,toolbar=yes,location=yes,directories=yes,status=yes,menubar=yes,scrollbars=yes,copyhistory=yes,resizable=yes');
}

function loadJob()
{
    var adNo = $.trim($('#jobAdNo').val());
    
    if(!isNaN(adNo) && adNo.length > 0)
    {
        $.ajax({
            type: "GET",
            url: '/XmlHttpProxy/fetch',
            data: { adno:adNo, format:'json'},
            contentType: "application/text; charset=utf-8",
            dataType: "json",
            error: function()
                   {
                        $('#displayJob').html('<span class="errror">Could not connect to Career Junction.</span>');
                   },
            success: function(inData)
                     {
                        if(inData.length>0)
                            parseJobJSON(inData);
                        else
                            $('#displayJob').html('<span class="error">Job not found.</span>');
                     }

        });
//        $.get(url,null,function(data){parseJobJSON(data);},'json');
    }
    else
    {
        $('#displayJob').html('<span class="error">Please enter a job ad number</span>');
    }
}

function parseJobJSON(jsonObject)
{
    if(jsonObject.length > 0)
    {
        var textBody = '<h2 style="color:#991111;">' + jsonObject[0].jobtitle + '</h2>';

        textBody += '<h3>Job Ad number:'+jsonObject[0].jobadno +'</h3>';
        textBody += '<p>' + jsonObject[0].jobmast + '</p>';
        textBody += '<p>';
        textBody += '<h3>Job description</h3>';
        textBody += jsonObject[0].candidatedescr;
        textBody += '</p>';

        if(jsonObject[0].companydescr.length > 0)
        {
            textBody += '<p><h3>The Company</h3>';
            textBody += jsonObject[0].companydescr;
            textBody += '</p>';
        }
        
        textBody += '<br/><br/><input type="button" class="button" onclick="gotToJobCJ('+jsonObject[0].jobadno+')" value="Apply">';

        $('#displayJob').html(textBody);
    }
    else
    {
        $('#displayJob').html('<strong style="color:red;">Job not found.</strong>');
    }
}



/*=======================================*/
/* END Career Junction API implementation*/
