jQuery(document).ready(function($){
    $.get("/stock/.FTAS,.FTSE,.DJI,.NYA,.INX",
    function(data){
        var data = eval(data.replace("//", ""))
        $(data).each(function(i, obj) {
            $("tr[rel="+obj.t+"]").find(".second").html(obj.l)
            $("tr[rel="+obj.t+"]").find(".third").html(obj.c+" ("+obj.cp+"%)")
        });
    });

    var currencies = ['EUR','USD','JPY','ZAR','HKD']
    for (var i=0; i < currencies.length; i++) {
        getCur(currencies[i])
    };

    function getCur(cur) {
        $.get("/currency/"+cur, function(data) {
            var res = eval(data);
            res = res.ResultSet.replace(/<\/?[^>]+>/gi, '')
            $("tr[rel="+cur+"]").find(".third").html(res)
        });
    } 

    $.ajax({
        type: "GET",
        url: "/weather",
        dataType: "xml",
        success: function(xml) {
            var this_date = new Date();
            $("li[rel=today]").html("TODAY "+this_date.getDate()+"."+(this_date.getMonth()+1)+"."+this_date.getFullYear().toString().substr(2,4))
            var days_of_the_week = new Array("SUN","MON","TUE","WED","THU","FRI","SAT")
            $(xml).find('forecast_conditions').each(function(i, obj) {
                var parent = $("ul[rel=weather_"+i+"]");
                var high = f2c($(this).find('high').attr("data"))
                var low  = f2c($(this).find('low').attr("data"))
                parent.find("span[rel=high]").html(high+"&deg;c")
                parent.find("span[rel=low]").html(low+"&deg;c")
                parent.find("img").attr("src", "http://www.google.com"+$(this).find("icon").attr("data"))
                parent.find("li[rel=highlow]").html(low+"/"+high+"&deg;c")
                parent.find("li[rel=date]").html(days_of_the_week[this_date.getDay()]+ " " +this_date.getDate())
                this_date.setTime(this_date.getTime(  ) + (1000*3600*24));
            })
        }
    }); 

    function f2c(value) {
        return Math.round((parseInt(value) - 32) * (5/9))
    }
    
    $(".text-field input, .text-field select").change(function() {
       updateCurrency();
    });
    
    function updateCurrency() {
        $.ajax({
             type: "POST",
             url: "/cur/"+$("#cur-to").val()+"/"+$("#cur-from").val()+"/"+$("#cur-val").val()+"",
             beforeSend: function() {
                 $("#cur-result").html("");
             },
             success: function(data){
                 var res = eval(data);
                 res = res.ResultSet.replace(/<\/?[^>]+>/gi, '')
                 $("#cur-result").html("&nbsp;="+res)
             }
           });
    }
    
    updateCurrency();
});
