$(document).ready(function($) {

  // Feedback form
  $('.site-map-feedback p.types a').click(function() {
    $('.site-map-feedback form').attr('action', 'http://projects.ajc.com/feedbackwidget/' + $(this).attr('id') + '/')
  });
  $('.site-map-feedback form').submit(function() {
    if ($('.site-map-feedback textarea').attr('defaultValue') != $('.site-map-feedback textarea').val()
    && $('.site-map-feedback input.email').attr('defaultValue') != $('.site-map-feedback input.email').val())
    {
      return true;
    }
    alert('Please enter your e-mail address and comment before submitting the form.')
    return false;
  });

	swapValues = [];
		jQuery(".swap_value").each(function(i){
		    swapValues[i] = jQuery(this).val();
		    jQuery(this).focus(function(){
		        if (jQuery(this).val() == swapValues[i]) {
		            jQuery(this).val("");
		        }
		    }).blur(function(){
		        if (jQuery.trim(jQuery(this).val()) == "") {
		            jQuery(this).val(swapValues[i]);
		        }
		    });
		});

	jQuery('div.ajc-sitemap textarea').focus(function() {
		jQuery(this).css('height','200px');
		jQuery('p.types').slideDown('fast');
	});

	jQuery('div.ajc-sitemap p.types a').bind('click', function() {
		jQuery('p.types a').removeClass('selected');
		jQuery(this).addClass('selected');
	});

    // Start more galleries slider
    $(".computers_technology").accessNews({
        newsHeadline: "",
        newsSpeed: "normal"
    });

    // Don't attempt to load gallery if feed isn't present
	if (gallery_json != '') {

		$.getJSON(gallery_json, function(data) {

			var gallery_size = $(data.media).length;
			var photo_index = 0;
			var gallery_url = window.location.href.split("#")[0];

			var gallery_split = gallery_url.split("/");
			var slug = gallery_split[gallery_split.length-2];
			var category = gallery_split[5];
			var subcategory = gallery_split[6];
			var full_category = (subcategory != slug) ? category + '/' + subcategory : category;
			
			var image_type = "slideshow";
			
			$('.controls').html('<span>1 of ' + gallery_size + '</span><a class=\"pprev\"><img src=\"http://alt.coxnewsweb.com/ajc/css/gallery2008/images/prev.gif\" width=\"20\" height=\"20\" alt=\"Previous\" title=\"Previous\" /></a>  <a class=\"pnext\"><img src=\"http://alt.coxnewsweb.com/ajc/css/gallery2008/images/next.gif\" width=\"20\" height=\"20\" alt=\"Next\" title=\"Next\" /></a>');

			$('#gallery-thumbnails').empty();
			$.each(data.media, function(entryIndex, entry) {
				$('#gallery-thumbnails').append('<img id=\"' + entryIndex + '\" src=\"' + entry['files']['thumbail'] + '\" width=\"54\" height=\"54\" />');
			});

			$('#gallery-thumbnails img:first-child').addClass('current');

			$('.pnext').bind('click', function() {
				if (photo_index < (gallery_size)) {
					photo_index++; changePhoto(photo_index);
				}
				else {	
				return false;
				}
			});

			$('.pprev').bind('click', function() {
				if (photo_index > 0) {
					photo_index--; changePhoto(photo_index);
				}
				else {	
				return false;
				}
			});

			$("#gallery-thumbnails img").click(function() {
				changePhoto(photo_index = parseInt($(this).attr('id')));
			});

			function sendAnalyticsEvent(accnt){
				
			    if(window.location.hash.indexOf("#homepage_tab") != -1 && photo_index == 1) {
			        var tab_tracking_value = window.location.hash.replace("#", '');
			        s_prop16 = "lk_"+tab_tracking_value;
			        try {
			            s_coxnews.prop16 = s_prop16;
			        }
			        catch(e) {
			        }
			    }
				else if(window.location.hash.indexOf("#sldr") != -1 && photo_index == 1) {
			        var tab_tracking_value = window.location.hash.replace("#", '');
			        s_prop16 = "lk_"+tab_tracking_value;
			        try {
			            s_coxnews.prop16 = s_prop16;
			        }
			        catch(e) {
			        }
				}
			    else {
			        s_prop16 = '';
			        try {
			            s_coxnews.prop16 = s_prop16;
			        }
			        catch(e) {
			        }
			    }
			    
			    if(photo_index == 1) {
			        //Blank prop24 (open) on second photo
			        s_coxnews.prop24 = '';
			    }

			    if(!accnt) {
			        accnt=s_account;
			    }

			    try {
			        void s_gs(accnt);
			    }
			    catch(e) {
			        s_coxnews.t();
			    }    
			}
			
			function end_of_gallery()
			{
                    $('h2:first').hide();
                    $('.related-links').hide();
                    $('.share').hide();
                    $('#photo-focal').hide();
                    $('#gallery-thumbnails').hide();
    				$('div.photo-caption').hide();
    				$('div.controls').hide();
					$('#hot_or_not_content').hide();


                    $('<div id=\"the-end\"></div>').appendTo('#gallery');

					$('<div class=\"restart-gallery\"></div>').appendTo('#the-end');

					$('<img>')
						.attr('src', $(data.media)[gallery_size-1]['files']['preview'])
						.attr('id','gallery-end-img')
						.width('145px')
						.css('opacity','0.3')
						.appendTo('div.restart-gallery');
					
					$('<p><a href="' + gallery_url + '"><img src=\"http://alt.coxnewsweb.com/ajc/css/gallery2008/images/restart-gallery-small.png\" /></a><br /><br/><a href="' + gallery_url + '">Restart Gallery</a></p>').css('width','145px').appendTo('div.restart-gallery');

                    $('<h3>' + $('#gallery h2').html() + '</h3>').appendTo('#the-end');

    			    $('#the-end').append('<div class=\"related-links\">' + $('div.related-links').html() + '</div>');
                    $('#the-end').append('<div class=\"share\"><ul><li class="email"><a href=\"#\" onclick=\"return(ET());\">E-mail</a></li><li class="prints"><a href=\"http://www.ajc.com/services/content/services/open/ajcstore/yourpix.html\">Order prints</a></li></ul></div>');

    				$('#the-end').append('<h3 class="related-galleries">More ' + gallery_category + ' Galleries</h3>');

					$('<div></div>')
						.load('/gallery/widget/thumbnails/28/'+ full_category + '.html')
						.appendTo('#gallery');
			}

			function html_entity_decode(str) {
			  var ta=document.createElement("textarea");
			  ta.innerHTML=str.replace(/</g,"&lt;").replace(/>/g,"&gt;");
			  return ta.value;
			}


			function changePhoto(photo_index)
			{

                // Don't advance if at end of gallery, instead show related galleries
				if ((photo_index) == gallery_size)
				{
					end_of_gallery();
					return false;
				}
				
					image_width 	= $(data.media)[photo_index]['files'][image_type + '-width'];
					image_height 	= $(data.media)[photo_index]['files'][image_type + '-height'];

						if (image_width > 0 && image_height > 0)
						{
							$('#photo-focal').html('<img id=\"image-' + photo_index + '\" width=\"' + image_width + '\" height=\"' + image_height + '\" src=\"' + $(data.media)[photo_index]['files'][image_type] + '\" alt=\"\" />');
						}
						else
						{
							$('#photo-focal').html('<img id=\"image-' + photo_index + '\" src=\"' + $(data.media)[photo_index]['files'][image_type] + '\" alt=\"\" />');	
						}


					$('.controls span')
						.html((photo_index + 1) + ' of ' + gallery_size);

					$('.photo-caption')
						.html(html_entity_decode($(data.media)[photo_index]['caption-site']).replace(/(<([^>]+)>)/ig,"") + ' <span>' + $(data.media)[photo_index]['credit-site'] + '</span>');

				photo_index == 0 ? $('.pprev').addClass('disabled') : $('.pprev').removeClass('disabled');
				photo_index == (gallery_size - 1) ? $('.pnext').addClass('disabled') : $('.pnext').removeClass('disabled');

				$('#gallery-thumbnails img').removeClass('current');
				$('#gallery-thumbnails img#' + photo_index).addClass('current');

				if (photo_index < 2)
				{
					yahoo_cstm_content_cat_list = ['position_'+(photo_index + 1)];
				}
				else {
					yahoo_cstm_content_cat_list = permanent_yahoo_cstm_content_cat_list;
				}
				
				// Refresh big box ad on first, second, and all odd photos
				if (photo_index == 1 || photo_index % 2 == 0)
				{	
          parent.big_box.location.replace('http://' + window.location.hostname + '/category/ad/?zone='+ad_targeting_zone+'&amp;ap='+ad_targeting_ap+'&amp;sub='+ad_targeting_sub+'&amp;pg='+ad_targeting_pg + '&amp;photo=' + (photo_index + 1) + '&amp;tile=1&amp;sz=300x250&amp;yahoo_site_section_name_list='+js_list_to_csv(yahoo_site_section_name_list)+'&amp;yahoo_cstm_content_cat_list='+js_list_to_csv(yahoo_cstm_content_cat_list)+'&amp;yahoo_content_type='+yahoo_content_type+'&amp;yahoo_content_topic_id_list='+js_list_to_csv(yahoo_content_topic_id_list));
				}

                // Refresh sponsored by ad on all photos
        parent.ad_90x35.location.replace('http://' + window.location.hostname + '/category/ad/?zone='+ad_targeting_zone+'&amp;ap='+ad_targeting_ap+'&amp;sub='+ad_targeting_sub+'&amp;pg='+ad_targeting_pg+'&amp;photo=' + (photo_index + 1) + '&amp;photogallery=spon&amp;fromsite=ajc&amp;tile=4&amp;sz=3x1&amp;yahoo_site_section_name_list='+js_list_to_csv(yahoo_site_section_name_list)+'&amp;yahoo_cstm_content_cat_list='+js_list_to_csv(yahoo_cstm_content_cat_list)+'&amp;yahoo_content_type='+yahoo_content_type+'&amp;yahoo_content_topic_id_list='+js_list_to_csv(yahoo_content_topic_id_list)+'&amp;yahoo_ad_size_list='+js_list_to_csv(['88x31']));

                // If hot or not enabled, reload it with unique id for each image
				if (typeof(so_for_blog) != 'undefined')
				{
					hotParams = so_for_blog.getParams()['FlashVars'].split('blogPollID=gallery_');
					so_for_blog.addParam("FlashVars", hotParams[0] + 'blogPollID=gallery_' + hotParams[1].split('_')[0] + ((photo_index == 0) ? '' : '_' + photo_index));
					so_for_blog.write("hot_or_not_content");
				}

                // Send metrics info for every image
				sendAnalyticsEvent();
			}

		});

	}

});

// Accessible News Slider (http://www.reindel.com/accessible_news_slider/)
// Used for more galleries list

jQuery.fn.accessNews = function(settings) {
    settings = jQuery.extend({
        newsHeadline: "Top Stories",
        newsSpeed: "normal"
    }, settings);
    return this.each(function(i) {
        aNewsSlider.itemWidth = parseInt(jQuery(".item:eq(" + i + ")",".news_slider").css("width")) + parseInt(jQuery(".item:eq(" + i + ")",".news_slider").css("margin-right"));
        aNewsSlider.init(settings,this);
        jQuery(".view_all > a", this).click(function() {
            aNewsSlider.vAll(settings,this);
            return false;
        });
    });
};
var aNewsSlider = {
    itemWidth: 0,
    init: function(s,p) {
        jQuery(".messaging",p).css("display","none");
        itemLength = jQuery(".item",p).length;
    /*    if (jQuery(".view_all",p).width() == null) {
            jQuery("#view",p).prepend("<p class='view_all'><a href='#'>View All</a></p>"); 
        } */
        newsContainerWidth = itemLength * aNewsSlider.itemWidth;
        jQuery(".container",p).css("width",newsContainerWidth + "px");
        jQuery(".next",p).css("display","block");
        animating = false;
        jQuery(".next",p).click(function() {
            if (animating == false) {
                animating = true;
                animateLeft = parseInt(jQuery(".container",p).css("left")) - (aNewsSlider.itemWidth * 2);
                if (animateLeft + parseInt(jQuery(".container",p).css("width")) > 0) {
                    jQuery(".prev",p).css("display","block");
                    jQuery(".container",p).animate({left: animateLeft}, s.newsSpeed, function() {
                        jQuery(this).css("left",animateLeft);
                        if (parseInt(jQuery(".container",p).css("left")) + parseInt(jQuery(".container",p).css("width")) <= aNewsSlider.itemWidth * 2) {
                            jQuery(".next",p).css("display","none");
                        }
                        animating = false;
                    });
                } else {
                    animating = false;
                }
            }
            return false;
        });
        jQuery(".prev",p).click(function() {
            if (animating == false) {
                animating = true;
                animateLeft = parseInt(jQuery(".container",p).css("left")) + (aNewsSlider.itemWidth * 2);
                if ((animateLeft + parseInt(jQuery(".container",p).css("width"))) <= parseInt(jQuery(".container",p).css("width"))) {
                    jQuery(".next",p).css("display","block");
                    jQuery(".container",p).animate({left: animateLeft}, s.newsSpeed, function() {
                        jQuery(this).css("left",animateLeft);
                        if (parseInt(jQuery(".container",p).css("left")) == 0) {
                            jQuery(".prev",p).css("display","none");
                        }
                        animating = false;
                    });
                } else {
                    animating = false;
                }
            }
            return false;
        });
    },
    vAll: function(s,p) {
        var o = p;
        while (p) {
            p = p.parentNode;
            if (jQuery(p).attr("class") != undefined && jQuery(p).attr("class").indexOf("news_slider") != -1) {
                break;
            }
        }
        if (jQuery(o).text().indexOf("View All") != -1) {
            jQuery(".next",p).css("display","none");
            jQuery(".prev",p).css("display","none");
            jQuery(o).text("View Less");
            jQuery(".container",p).css("left","0px").css("width",aNewsSlider.itemWidth * 2 + "px");
        } else {
            jQuery(o).text("View All");
            aNewsSlider.init(s,p);
        }
    }
};

// http://media.ajc.com/projects/zag/zag-cookie-parse.min.js
(function(){function f(k){var m=k+"=";var j=document.cookie.split(";");for(var l=0;l<j.length;l++){var n=j[l];while(n.charAt(0)===" "){n=n.substring(1,n.length)}if(n.indexOf(m)===0){return n.substring(m.length,n.length)}}return null}var c=f("zag");if(c&&(c.length>2)){while(c.charAt(0)==='"'){c=c.substring(1)}while(c.charAt(c.length-1)==='"'){c=c.substring(0,c.length-1)}var g={};var e=c.split("&");for(var b=0;b<e.length;b++){var h=e[b].indexOf("=");if(h<1){continue}var a=e[b].substring(0,h);var d=e[b].substring(h+1);if(!d){continue}g[a]=unescape(d)}window.zag=g}})();