var proxy = 'http://www.wthrsrc.info/uvi/proxy.aspx';
var proxyimgid = 'proxyimg';
var statres = '';
var polltimeout;
var polltimeout2;
var result;

$(document).ready(function() {
    // Get full path of local proxy resource
    statres = document.getElementById(proxyimgid).src;
});

function FillUVIData4Header(loc) { 
    $('body').css("cursor", "wait");
    getUVIData(loc);
    polltimeout = setTimeout('pollResponse4Header()', 250);
    $('body').css("cursor", "default");  
}

function FillUVIData4SunCare(loc) {
    $('body').css("cursor", "wait");
    getUVIData(loc);
    polltimeout2 = setTimeout('pollResponse4SunCare()', 250);
    $('body').css("cursor", "default");  
}

function getUVIData(loc) {
    // Prepare proxy submission
    statres = document.getElementById(proxyimgid).src;

    var fm = '<html><body onload="document.forms[0].submit();"><form method="get" action="' + proxy + '">';
    fm += '<input name="loc" value="' + loc + '">';
    fm += '<input name="res" value="' + statres + '">';
    fm += '</form></body></html>';

    // Remove proxy iframe
    $('#proxy').detach();
    
    // Add proxy iframe
    $('body').append('<iframe id="proxy" name="proxy" width="0" height="0" style="display: none; width: 0px; height: 0px" src="/blank.html"></iframe>');
    
    // Engage proxy
    var pframe = document.getElementById('proxy');
    if (pframe.contentWindow) pframe.contentWindow.location = pframe.src;
    pframe = (pframe.contentWindow) ? pframe.contentWindow : (pframe.contentDocument.document) ? pframe.contentDocument.document : pframe.contentDocument;
    pframe.document.open(); 
    pframe.document.write(fm);
    pframe.document.close();
    return false;
}

function pollResponse4Header() {
    //here it downloads the sun image to client in localhost debug mode
    if (window.frames[0].frames.length > 0) {

        if (window.frames[0].frames['uviresponse'].location.hash.length > 0)
            result = CleanUpUVjson(unescape(window.frames[0].frames['uviresponse'].location.hash.substr(1)));
        else
            return false;
      
        ////verify the entry 
        if (result.toString().toLowerCase().indexOf("unable") >= 0)
        {
            $("div#UVindex div.result ol.swatch li").removeClass("now");
            $("div#UVindex div.result ol.swatch li").removeClass("selected");
            $("div#UVindex div.result").hide();
            $("div#UVindex div.search").show();
            $("div.modal").show();
            $("div.modal p:eq(1)").hide();
            $("div.modal button").hide();
            $("div.modal p:eq(2)").html('City or zipcode you entered could not be found. Please try again.<br><br><button class="continue" value="continue" onclick=javascript:$(\"div.modal\").hide();>Continue</button>');

            return false;
        }
        /////

        var data = jQuery.parseJSON(result);

        //location
        var loc = data.location.toString().replace('+', ' ');
        $("div#UVindex div.result span#uvLocation").html(loc);
        setCookie('uvLoc', loc);
        
        //uvi
        var uviIndex = data.forecast[0].uvi.toString();
        $("div#UVindex div.result ol.swatch li").removeClass("now");
        $("div#UVindex div.result ol.swatch li").removeClass("selected");
        var index = uviIndex-1;
        
        $("div#UVindex div.result ol.swatch li:eq(" + index.toString() + ")").addClass("now");

        $("div#UVindex div.result dl").hide();

        $("div#UVindex div.result dl dt big").html(uviIndex);

        //date
        $("div#UVindex div.result b").html(dateFormat(data.forecast[0].date.toString(), 'dddd, mmmm d, yyyy'));

        FillHeaderUVDataImportancePublic(uviIndex);
        FillHeaderUVDataDescription(uviIndex);

        clearTimeout(polltimeout);
        return false;
    }
    else {

        polltimeout = setTimeout('pollResponse4Header()', 250);
        return false;
    }
}

function FillHeaderUVDataImportancePublic(index) {
    $.ajax({
        type: "GET",
        url: "/sun_care/uvIndexData.xml",
        dataType: "xml",
        success: function(xml) {
            $("div#UVindex div.result dl dt small").html($(xml).find("importancePublic:eq(" + index.toString() + ")").text().toUpperCase());
        }
    });
}

function FillHeaderUVDataDescription(index) {
    $.ajax({
        type: "GET",
        url: "/sun_care/uvIndexData.xml",
        dataType: "xml",
        success: function(xml) {
            $("div#UVindex div.result dl dd").html($(xml).find("description:eq(" + index.toString() + ")").text());
        }
    });
}

function pollResponse4SunCare() {

    if (window.frames[0].frames.length > 0) {

        // See if we have access to the hash yet
        try {
            window.frames[0].frames['uviresponse'].location.hash.length
        } catch (e) {
            // Thrown exception try to access the hash. Need to wait longer for the iframe to load
            polltimeout2 = setTimeout('pollResponse4SunCare()', 250);
            return false;
        }

        if (window.frames[0].frames['uviresponse'].location.hash.length > 0)
            result = CleanUpUVjson(unescape(window.frames[0].frames['uviresponse'].location.hash.substr(1)));
        else
            return false;

         
        ////verify the entry 
        // Make sure the result has a correct location. Check for location string ending with a comma
        if (result.toString().toLowerCase().indexOf("unable") >= 0) {
            displayError();
            return false;
        }
        /////
        var data = jQuery.parseJSON(result);
        
        //location
        var loc = data.location.toString().replace('+', ' ');
        loc = jQuery.trim(loc);
        if (loc.charAt(loc.length - 1) == ',') {
            displayError();
            return false;
        }

        $("div#tab1 div#UVresult b").html(loc);
         
        //uvi
        var uviIndex = data.forecast[0].uvi.toString();
        $("div#tab1 div#UVresult big").html(uviIndex);
        FillXmlUVData4SunCareDescription(uviIndex);
        FillSunCareUVDataImportancePublic4Today(uviIndex);
         
        //date
        var date = dateFormat(data.forecast[0].date.toString(), 'dddd, mmmm d');
        $("div#tab1 div#UVresult span.today h2").html("Today: " + date);

        var counter = 0;
        // Used to skip the current date
        var skipUVIndex = false;
        JSON.parse(result, function (key, value) {
            if (key == "date") {
                if (value.toString() != data.forecast[0].date.toString()) {
                    $("div#tab1 div#UVresult ul li:eq(" + counter + ")").html(dateFormat(value, 'ddd, mmm d'));
                } else { skipUVIndex = true; }
            }
            if (key == "uvi") {
                // Skip the current index because it's today's date
                if (skipUVIndex) { skipUVIndex = false; return; }
                uviIndex = value.toString();
                FillSunCareUVDataImportancePublic(uviIndex, counter); 
                // Only increment the counter each time we've inserted a UV index value
                counter++;
            }
        });

        clearTimeout(polltimeout2);
        return false;
    }
    else {
        polltimeout2 = setTimeout('pollResponse4SunCare()', 250);
        return false;
    }
}

function displayError() {
    $(this).parents("div#UVresult").hide();
    $("form[name='UVindex']").fadeIn();
    $('div#tab1 input').trigger('select');
    $("div#UVresult").hide();
    $("div#uv_error").show();
    if ($('#overlay').length > 0) {
        $('html, body').animate({
            scrollTop: $("body").offset().top
        }, 500);
        $('div#overlay').css('height', document.documentElement.scrollHeight);
        $("#overlay").fadeIn('fast');
    }

    return false;
}

function FillSunCareUVDataImportancePublic4Today(index) {
    $.ajax({
        type: "GET",
        url: "/sun_care/uvIndexData.xml",
        dataType: "xml",
        success: function (xml) {
            var importanceText = $(xml).find("importancePublic:eq(" + index.toString() + ")").text();
            $("div#tab1 div#UVresult p:eq(0) small").html(importanceText);
            $("div#tab1 div#UVresult p:eq(0)").removeClass();
            $("div#tab1 div#UVresult p:eq(0)").addClass("uv " + importanceText.toLowerCase());

        }

    });
}

function FillSunCareUVDataImportancePublic(index, itemIndex) {
    $.ajax({
        type: "GET",
        url: "/sun_care/uvIndexData.xml",
        dataType: "xml",
        success: function(xml) {
            var importanceText = $(xml).find("importancePublic:eq(" + index.toString() + ")").text();
            $("div#tab1 div#UVresult ul li:eq(" + itemIndex + ")").append("<p class='" + importanceText.toLowerCase() + "'>" + index.toString() + " " + importanceText + "</p>");

        }

    });
}

function CleanUpUVjson(response) {
        response = response.replace('<iframe name="uviresponse" id="uviresponse" src="#', '')
        response = response.replace('"></iframe>', '')
        response = response.replace('+', ' ')
        response = response.replace('DIF', '');
    return response;

}

function FillXmlUVData4SunCareDescription(uvIndex) {

    $.ajax({
        type: "GET",
        url: "uvIndexData.xml",
        dataType: "xml",
        success: function (xml) {
            $("div#tab1 div#UVresult p:eq(1)").html($(xml).find("description:eq(" + uvIndex + ")").text());
        }

    });
}

