jQuery(function($) {
    
    var alertsParent = $("#alerts_content");
    
    var isSmall = ($("#site_header").hasClass("small"));
    //  the url for the alert template needs the leading slash, otherwise the link is relative
    var alertTemplate = (isSmall) ? "/templates/alert_small.html" : "/templates/alert_big.html";
    
    // 1 // fetch the feed
    var feed = "/alerts_xml.php";
    var timeout = 20000;
    var oldAlertLength = 0;     
    
    
    function log(message)
    {               
        if (window.console && window.console.debug)
            window.console.debug(message);
    }  
    
    /**
     * Fetch the xml feed, show/hide the tab, add the new alerts to the container
     */
    function updateAlerts()
    {                          
        // preload the template
        $.template.load(alertTemplate, function(template) {     
            
          // fetch the feed
          $.get(feed, {}, function(data) {        
              
            // parse the xml
            var alerts = $(data).find("alert");

            $("#alerts_tab").text("Alerts ("+alerts.length+")");

            (alerts.length > 0) ? $("#alerts_tab").show() : $("#alerts_tab").hide();

            // setTimeout(updateAlerts, timeout);   
            
            // skip if the alerts haven't changed. Assuming it is unlikely we will ever add one then remove one in one interval, so if the number changes, then we update
            if (oldAlertLength == alerts.length)
                return;  

            else if (alerts.length > oldAlertLength)
                $("#site_header_pages").navigate("alerts");

            oldAlertLength = alerts.length;           



            // remove the old navigation and alerts
            $("div", alertsParent).remove();
            $("#alerts_nav a").remove();

            // add the new alerts
            for (var i=0; i < alerts.length; i++)
            {
                var alert = $(alerts[i]);
                var victim = alert.find('victim:first');
                var suspect = alert.find('suspect:first');
                var location = alert.find('location:first'); 
     			var agency = alert.find('agency:first');
                         
                // massage the data to make it easier for the templates
                var data = {
                    link: "/alerts/" + alert.attr('uid'),

                    incident: {                                
                        summary: alert.attr("incidentSummary"),
                        caseNumber: alert.attr("localCase"),
                        lastSeen: alert.attr("incidentDate"),  
                        lat: location.attr('latitude'),
                        lon: location.attr('longitude'),
                        city: location.attr('city'),
                        province: location.attr('province'),
                        location: location.attr('city') + ", " + location.attr('province'),
						phone: agency.attr('publicPhone')
                    },

                    victim: {
                        image: victim.attr('thumbnailURL'),
                        fullName: victim.attr('firstName') + " " + victim.attr('lastName'),
                        age: victim.attr('age') + " " + victim.attr('ageType'),
                        dob: victim.attr('dob'),
                        height: victim.attr('heightFt') + "' " + victim.attr('heightIn') + "\"",
                        weight: victim.attr('weight') + " lbs", 
                        hair: victim.attr('hairColor'),
                        eyes: victim.attr('eyeColor')
                    },

                    suspect: {
                        image: suspect.attr('thumbnailURL'),
                        fullName: suspect.attr('firstName') + " " + suspect.attr('lastName'),
                        age: suspect.attr('age') + " " + suspect.attr('ageType'),
                        dob: suspect.attr('dob'),
                        height: suspect.attr('heightFt') + "' " + suspect.attr('heightIn') + "\"",
                        weight: suspect.attr('weight') + " lbs", 
                        hair: suspect.attr('hairColor'),
                        eyes: suspect.attr('eyeColor')
                    }
                }          

                // run the templates
                $.template.run(alertTemplate, data, function(result) {   
                    alertsParent.append(result);
                });                
            }

           $("#alerts_content").cycle({
               fx:"scrollHorz",
               timeout: 0,  
               pager: "#alerts_nav",
               next: "#alerts_next",
               prev: "#alerts_prev"
           });
           $("#alerts_content .ambermap").ambermap();    

          }, "xml");
        });
    }
    
    $("#alerts_tab").hide(); // hide it to start
    updateAlerts();
    
  
    
      $("#alerts_content").cycle({
         fx:"scrollHorz",
         timeout: 0,  
         pager: "#alerts_nav",
         next: "#alerts_next",
         prev: "#alerts_prev"
      }); // works fine, but the nav stuff doesn't!
    
    
    
      
    
    
    








    // Navigation with custom effect
    var nav = $("#site_header_pages").navigation();
    
    $.navigation = {
        hide: function(obj) {
            obj.fadeOut();
        },
        show: function(obj) {
            obj.fadeIn();
        }
    }
    
    
    
    
    
    
    // Rounded Corners
    $("#site_header_content").corner("tl 20px");
    $("#site_header_pages").corner("tl 20px");
    $("#site_header_links").corner("bl br 20px");
    $("#site_header_links ul").prepend('<li class="link_border"></li>');










    // Clickable Images // 
    $(".bgimageclick").each(function() {
        var current_url = window.location.href;
        
        var insecure_url = "http://s7.amberalert.com/media/images/" + $(this).attr("image");
        var secure_url = "https://dev-01-public.s3.amazonaws.com/media/images/" + $(this).attr("image");
        
        var url = (current_url.match("https") ? secure_url : insecure_url);
        
        $(this).css("background-image","url("+url+")");
        $(this).css("background-repeat","no-repeat");
        $(this).css("cursor","pointer");
        $(this).click(function() {
            window.location = $(this).attr("link");
            return false;
        });
    })
})