﻿



ddaccordion.init({
headerclass: "silverheader", //Shared CSS class name of headers group
contentclass: "submenu", //Shared CSS class name of contents group
revealtype: "mouseover", //Reveal content when user clicks or onmouseover the header? Valid value: "click", "clickgo", or "mouseover"
mouseoverdelay: 200, //if revealtype="mouseover", set delay in milliseconds before header expands onMouseover
collapseprev: true, //Collapse previous content (so only one open at any time)? true/false
defaultexpanded: [0], //index of content(s) open by default [index1, index2, etc] [] denotes no content
onemustopen: true, //Specify whether at least one header should be open always (so never all headers closed)
animatedefault: false, //Should contents open by default be animated into view?
persiststate: true, //persist state of opened contents within browser session?
toggleclass: ["", "selected"], //Two CSS classes to be applied to the header when it's collapsed and expanded, respectively ["class1", "class2"]
togglehtml: ["", "", ""], //Additional HTML added to the header when it's collapsed and expanded, respectively  ["position", "html1", "html2"] (see docs)
animatespeed: "normal", //speed of animation: integer in milliseconds (ie: 200), or keywords "fast", "normal", or "slow"
oninit:function(headers, expandedindices){ //custom code to run when headers have initalized
    //do nothing
},
onopenclose:function(header, index, state, isuseractivated){ //custom code to run whenever a header is opened or closed
    //do nothing
}
})


if(window.location.href.indexOf("www.vintonweather.com") == -1)
{
    window.location.href = 'http://www.vintonweather.com';
}

var xml = "";
var serviceStr = "http://www.vintonweather.com/services/weatherxmlprovider.asmx/GetXMLString";
$('#mainBody').width(screen.width).height(screen.height);
$(document).ready(function() {

    LoadXML();

    showHistoryGraph('outsideTemp', 'http://www.vintonweather.com/wx/OutsideTempHistory.gif');
    showHistoryGraph('outsideDewPt', 'http://www.vintonweather.com/wx/DewPointHistory.gif');
    showHistoryGraph('windChill', 'http://www.vintonweather.com/wx/WindChillHistory.gif');
    showHistoryGraph('thw', 'http://www.vintonweather.com/wx/THWHistory.gif');
    showHistoryGraph('outsideHeatIndex', 'http://www.vintonweather.com/wx/HeatIndexHistory.gif');
    showHistoryGraph('outsideHumidity', 'http://www.vintonweather.com/wx/OutsideHumidityHistory.gif');
    showHistoryGraph('windSpeed', 'http://www.vintonweather.com/wx/WindSpeedHistory.gif');
    showHistoryGraph('uv', 'http://www.vintonweather.com/wx/UVHistory.gif');
    showHistoryGraph('solarRad', 'http://www.vintonweather.com/wx/SolarRadHistory.gif');
    showHistoryGraph('barometer', 'http://www.vintonweather.com/wx/BarometerHistory.gif');
    showHistoryGraph('dailyRain', 'http://www.vintonweather.com/wx/RainHistory.gif');
    showHistoryGraph('rainRate', 'http://www.vintonweather.com/wx/RainRateHistory.gif');


    LoadWatchesandWarnings();

    LoadForecast();
    $('#wximage').qtip({ content: '<img src="http://www.vintonweather.com/wxcam/image.jpg"/>', style: { width: 680 }, position: { corner: { target: 'rightBottom', tooltip: 'leftTop'}} });            

    $("#CurrentConditons").fadeIn();
    $("#CurrentConditionsBtn").click(function() {
        switcharea();
        showarea('CurrentConditions');
        LoadForecast();
    });
    $("#WatchWarnBtn").click(function() {
        switcharea();
        showarea('WatchWarn');
        LoadWatchesWarnings();
    });
    $("#SPCBtn").click(function() {
        switcharea();
        showarea('SPC');
        LoadSPC();
    });
    $("#SpotterBtn").click(function() {
        switcharea();
        showarea('Spotter');
    });
    $("#LightningBtn").click(function() {
        switcharea();
        showarea('Lightning');
    });
    $("#LinkBtn").click(function() {
        switcharea();
        showarea('Links');
    });
    $("#HurricaneBtn").click(function() {
        switcharea();
        showarea('Hurricane');
        LoadHurricane();
    });
})

function LoadXML() {
    $.ajax({
        type: "POST",
        url: serviceStr,
        data: '{"xmlID":"1"}',
        contentType: "application/json; charset=utf-8",
        dataType: "xml",
        success: function(str) { Process(str); 
        d = new Date();
        $("#wximage").attr('src','http://www.vintonweather.com/wxcam/image.jpg?' + d.getTime());
        }
    });
    setTimeout('LoadXML()', 60000);
    setTimeout('checkXML()', 2500);
}

function checkXML() {
    if ($('#outsideTemp').html() == '') {
        LoadXML();
    }
}

function LoadWatchesandWarnings() {
    $.ajax({
        type: "POST",
        url: serviceStr,
        data: '{"xmlID":"10"}',
        contentType: "application/json; charset=utf-8",
        dataType: "xml",
        success: function(str) { WxAlert(str, 'BlackHawkTC'); }

    });
    $.ajax({
        type: "POST",
        url: serviceStr,
        data: '{"xmlID":"8"}',
        contentType: "application/json; charset=utf-8",
        dataType: "xml",
        success: function(str) { WxAlert(str, 'BentonTC'); }

    });
                $.ajax({
        type: "POST",
        url: serviceStr,
        data: '{"xmlID":"11"}',
        contentType: "application/json; charset=utf-8",
        dataType: "xml",
        success: function(str) { WxAlert(str, 'TamaTC'); }

    });
                $.ajax({
        type: "POST",
        url: serviceStr,
        data: '{"xmlID":"9"}',
        contentType: "application/json; charset=utf-8",
        dataType: "xml",
        success: function(str) { WxAlert(str, 'LinnTC'); }

    });
                $.ajax({
        type: "POST",
        url: serviceStr,
        data: '{"xmlID":"13"}',
        contentType: "application/json; charset=utf-8",
        dataType: "xml",
        success: function(str) { WxAlert(str, 'BuchananTC'); }

    });
                $.ajax({
        type: "POST",
        url: serviceStr,
        data: '{"xmlID":"12"}',
        contentType: "application/json; charset=utf-8",
        dataType: "xml",
        success: function(str) { WxAlert(str, 'PoweshiekTC'); }

    });
    setTimeout('LoadWatchesandWarnings()', 120000);

}

function WxAlert(str, id) {
    var displayStr = "";
    $(str).find('entry').each(function() {
        var title = $(this).find('title').text();
        var summary = $(this).find('summary').text();
        if (title.toLowerCase().indexOf("there are no active watches, warnings or advisories") != -1) {
            displayStr = "There are no active watches, warnings or advisories";
        } else {
            var advisoryURL = $(this).find('id').text();
            var start = advisoryURL.indexOf("?x=") + 3;
            var qs = advisoryURL.substring(start);
            $.ajax({
                type: "POST",
                url: "http://www.vintonweather.com/services/weatherxmlprovider.asmx/GetAdvisory",
                data: '{"x":"' + qs + '"}',
                contentType: "application/json; charset=utf-8",
                dataType: "xml",
                async: false,
                success: function(rstr) {
                    var title2 = $(rstr).find('headline').text();
                    var summary2 = $(rstr).find('description').text();
                    if (title2.toLowerCase().indexOf('warning') >= 0) {
                        $('#' + id).css('background-color', 'red');
                    } else {
                        $('#' + id).css('background-color', 'goldenrod');
                    }
                    displayStr += '<b>' + title2 + '</b><br/>' + summary2 + '<br/><br/>';
                }
            });
        }
    });
    $('#' + id).qtip({ content: displayStr, style: {width:500},position: { corner: { target: 'bottomMiddle', tooltip: 'topRight'}} });
}

var forecastXML = "";
function LoadForecast() {
    $.ajax({
        type: "POST",
        url: serviceStr,
        data: '{"xmlID":"5"}',
        contentType: "application/json; charset=utf-8",
        dataType: "xml",
        success: function(str) { FillForecast(str); $('#darkLayer').hide(); }

    });
}

var wwXML = "";
function LoadWatchesWarnings() {
    $.ajax({
        type: "POST",
        url: serviceStr,
        data: '{"xmlID":"2"}',
        contentType: "application/json; charset=utf-8",
        dataType: "xml",
        success: function(str) { FillWatchWarn(str); $('#darkLayerWW').hide(); }

    });
    setTimeout('LoadWatchesWarnings()', 120000);
}

var spcXML = "";
function LoadSPC() {
    $.ajax({
    type: "POST",
    url: serviceStr,
    data: '{"xmlID":"3"}',
    contentType: "application/json; charset=utf-8",
    dataType: "xml",
    success: function(str) { FillSPC(str); $('#darkLayerSPC').hide(); }
    });
    setTimeout('LoadSPC()', 300000);
}

var hurricaneXML = "";
function LoadHurricane() {
    $.ajax({
        type: "POST",
        url: serviceStr,
        data: '{"xmlID":"4"}',
        contentType: "application/json; charset=utf-8",
        dataType: "xml",
        success: function(str) { FillHurricane(str); $('#darkLayerHurr').hide(); }

    });
}

var floodXML = "";

function getWeatherValue(val) { return $(xml).find(val).text(); }

function Process(str)
{
    xml = str;
    $('.wxdata').each(function() { $(this).html(getWeatherValue($(this).attr('id')) + ' ' + getWeatherValue($(this).attr('mValue'))); });
    $('.wxdata_dt').each(function() { $(this).html(getWeatherValue($(this).attr('id')) + ' ' + getWeatherValue($(this).attr('mValue')) + ' @ ' + getWeatherValue($(this).attr('tName'))); });

    $('#windSpeed').html(getWeatherValue('windDirection') + ' @ ' + $('#windSpeed').html());
    
    $('#HighLows1').fadeIn(); $('#HighLows2').fadeIn(); $('#HighLows3').fadeIn(); $('#HighLows4').fadeIn();

    var date = getWeatherValue('date');
    var year = '20' + date.substring(6);
    date = date.substring(0, 6) + year;
    var time = getWeatherValue('time').replace('a', ' am').replace('p', ' pm');
    var datetimestamp = new Date(date + ' ' + time);
    if (((new Date() - datetimestamp) / 60000) > 15) {
        $('#headerText').html('<span style="color:red;">Current Conditions are out of date.</span>').fadeIn();
    }
    else
    {
        $('#headerText').html('Current Conditions<Br/><span>as of ' + datetimestamp.format() + '</span>').fadeIn();
   

        var windSpeed = getWeatherValue('windSpeed');
        var temp = getWeatherValue('outsideTemp');
        var rain = getWeatherValue('dailyRain');
        var data1 = new google.visualization.DataTable();
        data1.addColumn('string', 'Label');
        data1.addColumn('number', 'Value');
        data1.addRows(1);
        data1.setValue(0, 0, 'Wind');
        data1.setValue(0, 1, parseFloat(windSpeed));

        var chart1 = new google.visualization.Gauge(document.getElementById('chart_div1'));
        var options1 = { width: 150, height: 145, min: 0, max: 80, redFrom: 60, redTo: 80,
            yellowFrom: 40, yellowTo: 80, minorTicks: 5, majorTicks: ['0', '10', '20', '30', '40', '50', '60', '70', '80']
        };
        chart1.draw(data1, options1);


        var data2 = new google.visualization.DataTable();
        data2.addColumn('string', 'Label');
        data2.addColumn('number', 'Value');
        data2.addRows(1);
        data2.setValue(0, 0, 'Temp');
        data2.setValue(0, 1, parseFloat(temp));

        var chart2 = new google.visualization.Gauge(document.getElementById('chart_div2'));
        var options2 = { width: 150, height: 145, min: -20, max: 120, redFrom:90, redTo:120,
        minorTicks: 5, majorTicks: ['-20', '-10', '0', '10', '20', '30', '40', '50', '60', '70', '80', '90', '100', '110', '120']
        };
       chart2.draw(data2, options2);

        var data3 = new google.visualization.DataTable();
        data3.addColumn('string', 'Label');
       data3.addColumn('number', 'Value');
        data3.addRows(1);
        data3.setValue(0, 0, 'Rain');
        data3.setValue(0, 1, parseFloat(rain));

        var chart3 = new google.visualization.Gauge(document.getElementById('chart_div3'));
        var options3 = { width: 150, height: 145, min: 0, max: 5,
            minorTicks: .5, majorTicks: ['0', '1', '2', '3', '4', '5']
        };
        chart3.draw(data3, options3);
    }
}       
function FillWatchWarn(str) {
    wwXML = str;
    $('#WatchWarnDiv').html("");
    $(wwXML).find('item').each(function() {
    $('#WatchWarnDiv').append($(this).find('pubDate').text() + '<br/><b><a target="_blank" href="' + $(this).find('link').text() + '">' + $(this).find('title').text() + '</a></b><br/><hr/>');
    });
}

function FillSPC(str) {
    spcXML = str;
    $('#SPCDiv').html("");
    $(spcXML).find('item').each(function() {
    $('#SPCDiv').append($(this).find('pubDate').text() + '<br/><b><a target="_blank" href="' + $(this).find('link').text() + '">' + $(this).find('title').text() + '</a></b><br/>' + $(this).find('description').text() + '<br/><hr/>');
    });
}

function FillHurricane(str) {
    hurricaneXML = str;
    $('#HurrDiv').html("");
    $(hurricaneXML).find('item').each(function() {
    $('#HurrDiv').append($(this).find('pubDate').text() + '<br/><b><a target="_blank" href="' + $(this).find('link').text() + '">' + $(this).find('title').text() + '</a></b><br/>' + $(this).find('description').text() + '<br/><hr/>');
    });
}

function showHistoryGraph(idname, imgname) {
    $('#' + idname).qtip({ content: '<img src="' + imgname + '"/>', style: { width: 350 }, position: { corner: { target: 'rightMiddle', tooltip: 'leftMiddle'}} });
}

function FillForecast(str) {
    $.ajax({
        type: "POST",
        url: serviceStr,
        data: '{"xmlID":"6"}',
        async: false,
        contentType: "application/json; charset=utf-8",
        dataType: "xml",
        success: function(str) { floodXML = str; $('#darkLayer').hide(); }
    });

    forecastXML = str;
    $('#forecastStr').html('');
    $(forecastXML).find('forecastday').each(function() {
        if ($(this).find('title').text() != "") {
            $('#forecastStr').append('<br/><b>' + $(this).find('title').text() + ':</b> ' + $(this).find('fcttext').text() + '<br/>');
        }
    });
    var simpleForecast = $(forecastXML).find('simpleforecast');
    var moonphase = $(forecastXML).find('moon_phase');
    var moon_perill = $(moonphase).find('percentIlluminated').text();
    var moon_age = $(moonphase).find('ageOfMoon').text();
    var sunset_hour = $(moonphase).find('sunset').find('hour').text();
    var sunset_minute = $(moonphase).find('sunset').find('minute').text();
    var sunrise_hour = $(moonphase).find('sunrise').find('hour').text();
    var sunrise_minute = $(moonphase).find('sunrise').find('minute').text();

    $('#forecastStr').append('<br/><br/><span style="color:black;font-size:14pt;">Almanac</span><br/><b>Sunset:</b> ' + sunset_hour + ":" + sunset_minute);
    $('#forecastStr').append('<br/><b>Sunrise:</b> ' + sunrise_hour + ":" + sunrise_minute);
    $('#forecastStr').append('<br/><b>Moon:</b> ' + moon_perill + '% Illuminated and ' + moon_age + ' days old.');
    $('#forecastStr').append('<br/><br/><span style="color:black;font-size:14pt;">River Conditions</span><br/><b>Cedar River at Vinton:</b>' + $(floodXML).find('item').find('description').text());

    $(simpleForecast).find('forecastday').each(function() {
        var weekDay = $(this).find('weekday').text();
        var id = $(this).find('period').text();
        var high = $(this).find('high').find('fahrenheit').text();
        var low = $(this).find('low').find('fahrenheit').text();
        var iconImg = "";
        var icon = $(this).find('icon_set').each(function() {
            if ($(this).attr("name") == "Default") {
                iconImg = $(this).text();
            }
        });
        $('#forecast' + id).html('');
        $('#forecast' + id).append('<center><img border=1 src="' + iconImg + '"/><br/><b>' + weekDay + '</b><br/>High:' + high + 'ºF<br/>Low:' + low + 'ºF</center>');
    });
    
}


function reloadRadar() {
    d = new Date();
    $("#radarImg").attr('src','http://radblast.wunderground.com/cgi-bin/radar/WUNIDS_composite?centerlat=42.2&centerlon=-92.0&radius=150&width=550&height=400&type=N0R&frame=0&num=10&delay=10&newmaps=1&r=1249229266&' + d.getTime());
    setTimeout('reloadRadar()', 300000);
    }
    
function switcharea()
{
    $("#CurrentConditions").hide();
    $("#WatchWarn").hide();
    $("#Links").hide();
    $("#Hurricane").hide();
    $("#SPC").hide();
    $("#Spotter").hide();
    $("#Lightning").hide();


    
}

function showarea(id)
{
    $("#" + id).fadeIn();
}

/*
* Date Format 1.2.3
* (c) 2007-2009 Steven Levithan <stevenlevithan.com>
* MIT license
*
* Includes enhancements by Scott Trenda <scott.trenda.net>
* and Kris Kowal <cixar.com/~kris.kowal/>
*
* Accepts a date, a mask, or a date and a mask.
* Returns a formatted version of the given date.
* The date defaults to the current date/time.
* The mask defaults to dateFormat.masks.default.
*/

var dateFormat = function() {
    var token = /d{1,4}|m{1,4}|yy(?:yy)?|([HhMsTt])\1?|[LloSZ]|"[^"]*"|'[^']*'/g,
		timezone = /\b(?:[PMCEA][SDP]T|(?:Pacific|Mountain|Central|Eastern|Atlantic) (?:Standard|Daylight|Prevailing) Time|(?:GMT|UTC)(?:[-+]\d{4})?)\b/g,
		timezoneClip = /[^-+\dA-Z]/g,
		pad = function(val, len) {
		    val = String(val);
		    len = len || 2;
		    while (val.length < len) val = "0" + val;
		    return val;
		};

    // Regexes and supporting functions are cached through closure
    return function(date, mask, utc) {
        var dF = dateFormat;

        // You can't provide utc if you skip other args (use the "UTC:" mask prefix)
        if (arguments.length == 1 && Object.prototype.toString.call(date) == "[object String]" && !/\d/.test(date)) {
            mask = date;
            date = undefined;
        }

        // Passing date through Date applies Date.parse, if necessary
        date = date ? new Date(date) : new Date;
        if (isNaN(date)) throw SyntaxError("invalid date");

        mask = String(dF.masks[mask] || mask || dF.masks["default"]);

        // Allow setting the utc argument via the mask
        if (mask.slice(0, 4) == "UTC:") {
            mask = mask.slice(4);
            utc = true;
        }

        var _ = utc ? "getUTC" : "get",
			d = date[_ + "Date"](),
			D = date[_ + "Day"](),
			m = date[_ + "Month"](),
			y = date[_ + "FullYear"](),
			H = date[_ + "Hours"](),
			M = date[_ + "Minutes"](),
			s = date[_ + "Seconds"](),
			L = date[_ + "Milliseconds"](),
			o = utc ? 0 : date.getTimezoneOffset(),
			flags = {
			    d: d,
			    dd: pad(d),
			    ddd: dF.i18n.dayNames[D],
			    dddd: dF.i18n.dayNames[D + 7],
			    m: m + 1,
			    mm: pad(m + 1),
			    mmm: dF.i18n.monthNames[m],
			    mmmm: dF.i18n.monthNames[m + 12],
			    yy: String(y).slice(2),
			    yyyy: y,
			    h: H % 12 || 12,
			    hh: pad(H % 12 || 12),
			    H: H,
			    HH: pad(H),
			    M: M,
			    MM: pad(M),
			    s: s,
			    ss: pad(s),
			    l: pad(L, 3),
			    L: pad(L > 99 ? Math.round(L / 10) : L),
			    t: H < 12 ? "a" : "p",
			    tt: H < 12 ? "am" : "pm",
			    T: H < 12 ? "A" : "P",
			    TT: H < 12 ? "AM" : "PM",
			    Z: utc ? "UTC" : (String(date).match(timezone) || [""]).pop().replace(timezoneClip, ""),
			    o: (o > 0 ? "-" : "+") + pad(Math.floor(Math.abs(o) / 60) * 100 + Math.abs(o) % 60, 4),
			    S: ["th", "st", "nd", "rd"][d % 10 > 3 ? 0 : (d % 100 - d % 10 != 10) * d % 10]
			};

        return mask.replace(token, function($0) {
            return $0 in flags ? flags[$0] : $0.slice(1, $0.length - 1);
        });
    };
} ();

// Some common format strings
dateFormat.masks = {
    "default": "ddd mmm dd yyyy HH:MM:ss",
    shortDate: "m/d/yy",
    mediumDate: "mmm d, yyyy",
    longDate: "mmmm d, yyyy",
    fullDate: "dddd, mmmm d, yyyy",
    shortTime: "h:MM TT",
    mediumTime: "h:MM:ss TT",
    longTime: "h:MM:ss TT Z",
    isoDate: "yyyy-mm-dd",
    isoTime: "HH:MM:ss",
    isoDateTime: "yyyy-mm-dd'T'HH:MM:ss",
    isoUtcDateTime: "UTC:yyyy-mm-dd'T'HH:MM:ss'Z'"
};

// Internationalization strings
dateFormat.i18n = {
    dayNames: [
		"Sun", "Mon", "Tue", "Wed", "Thu", "Fri", "Sat",
		"Sunday", "Monday", "Tuesday", "Wednesday", "Thursday", "Friday", "Saturday"
	],
    monthNames: [
		"Jan", "Feb", "Mar", "Apr", "May", "Jun", "Jul", "Aug", "Sep", "Oct", "Nov", "Dec",
		"January", "February", "March", "April", "May", "June", "July", "August", "September", "October", "November", "December"
	]
};

// For convenience...
Date.prototype.format = function(mask, utc) {
    return dateFormat(this, mask, utc);
};
