// --------------------------------------------------------
// Used in Default.aspx
// --------------------------------------------------------

var Homepage = {
	show_loading_screen : function () {
        $('#container_left').unblock({ fadeOut : 0 }).block({ 
            message: '<div class="loading"><img src="common/images/ajax_loader.gif" /> Loading...</div>' , 
            css : {        
                left   : '5%',
                border : '0px solid #a00',
                width  : '100px',
                height : '40px'
            },
            overlayCSS : { 
                backgroundColor : '#fff', 
                opacity         : '0.5' 
            }
        });    
    },
    hide_loading_screen : function () {
		$('#container_left').unblock(); 
    }
};

var HomepageArticlePopup = {
    _article_ids : {},

    // keep a mapping of the article
    // types (most_recommended, etc)
    // and the current set of article 
    // ids being displayed. The show()
    // function uses this.
	set_article_ids : function (ids) { HomepageArticlePopup._article_ids = ids  },
	get_article_ids : function ()    { return HomepageArticlePopup._article_ids },

    show : function (article_placement) {
		Homepage.show_loading_screen(); 
        HomepageArticlePopup.load_article(
			HomepageArticlePopup._article_ids[article_placement],
			article_placement, 
			HomepageArticlePopup._show_popup
        );   
    },
    
    _show_popup : function () {
		$('#container_left').unblock({ fadeOut : 0 }).block({ 
			message : $('#article_popup'), 
			css : {        
				left   : '5%',
				border : '0px solid #a00',
				width  : '500px'
			}
		});
	},
	
	load_simple_article : function (article_id, element) {
		HomepageArticlePopup.load_article(article_id);
		$(element).parent().parent().find('li.current').removeClass('current');
		$(element).parent().addClass('current');
	},
    
    load_article : function (article_id, article_placement, callback) {
		var post_data;
		var post_url;
		
		if (article_placement == undefined) {
			post_url        = "/WebServices/HomepageArticles.asmx/GetArticleById";
			post_data       = "{article_id:\"" + article_id + "\"}";
		}
		else {
			post_url  = "/WebServices/HomepageArticles.asmx/GetArticleByIdWithNextArticles";
			post_data = "{article_id:\"" + article_id + 
			      "\",location:\"" + article_placement + 
			      "\",category_name:\"" + HomepageImages.get_current_category_name() + 
			      "\"}";
		}
		$.ajax({ 
			type        : "post",
			url         : post_url,
			data        : post_data,
			contentType : "application/json; charset=UTF-8",
			success     : function (response_text) {   
				HomepageArticlePopup.display_article(
					article_id,
					JSON.parse(response_text)
				);
				if (callback) callback();
			}
		});
    },
    
    display_article : function (article_id, data) {
		$('#article_popup .content .text_left p').html( data["intro"] );
		$('#article_popup .content .text_left .link a').attr( 'href', data["article_link"] );
		$('#article_popup .heading h3').html( data["title"] );
		$('#article_popup .content').css( 'background-image', 'url(' + data["large_image"] + ')' );
		HomepageArticlePopup.display_related_articles(
			$('#article_popup .content .text_left .related_article_container'), 
			data["related_articles"]
		);
		// only change these when we need too
		if (data["next_articles"] != undefined) {
			HomepageArticlePopup.display_next_articles(
				$('#article_popup .content .text_left .article_controls'),
				article_id, 
				data["next_articles"]
			);
		}
    },
    
    display_related_articles : function (parent, related_articles) {
		var list_container = $('ul', parent);
		var output = '';
		$.each(related_articles, function () {
			output += '<li class="related_articles"><a href="' + this['url'] + '">' + this['title'] + '</a></li>';
		});
		list_container.html(output);
	},
	
	display_next_articles : function (parent, article_id, next_articles) {
		var list_container = $('ul', parent);
		var output = '<li class="current"><a href="javascript:void(0)" onclick="HomepageArticlePopup.load_simple_article(' + article_id + ', this)">1</a></li>';
		$.each(next_articles, function (i, val) {
			output += '<li><a href="javascript:void(0)" onclick="HomepageArticlePopup.load_simple_article(' + val + ', this)">' + (i + 2) + '</a></li>';
		});
		list_container.html(output);
	}
};

var HomepageImages = {
    _cache                 : {},
	_current_category_name : "",
	
    // cache for JSON, so we don't 
    // need to keep calling the Ajax
    has_cache_for : function (k)    { return HomepageImages._cache[k] != undefined },
    set_cache_for : function (k, v) { HomepageImages._cache[k] = v                 },
    get_cache_for : function (k)    { return HomepageImages._cache[k]              },

	get_current_category_name : function () { 
		return HomepageImages._current_category_name 
	},

    change_images : function (category_id) {
        Homepage.show_loading_screen();
        
        // extract the default 
        // set and cache it
        if (!HomepageImages.has_cache_for('all')) {
            HomepageImages.set_cache_for('all', HomepageImages.extract_default_article_set());
        }
        
        HomepageImages._current_category_name = category_id;
        
        // if we have it in the cache ...
        if (HomepageImages.has_cache_for(category_id)) {
            HomepageImages.apply_article_set(HomepageImages.get_cache_for(category_id));
            Homepage.hide_loading_screen();
            return;
        }
        
        $.ajax({ 
            type: "post",
            url: "/WebServices/HomepageArticles.asmx/ByCategory",
            data: "{category:\"" + category_id + "\"}",
            contentType: "application/json; charset=UTF-8",
            success: function (response_text) {
			    var data = JSON.parse(response_text);
                HomepageImages.set_cache_for( category_id, data ); 
                HomepageImages.apply_article_set( data ); 
                Homepage.hide_loading_screen();       
            }
        });
    },

    // applying a new data set
    apply_article_set : function (data) {  
      
        // most recommended
        $('#divOne').css('background-image', 'url(' + data["most_recommended"]["image"] + ')');
        $('#divOne .orange_bg span').html(data["most_recommended"]["title"]);
        $('#divOne .trans_bg div').eq(0).html(data["most_recommended"]["intro"]);
            
        // featured 
        $('#divTwo .image img').attr('src', data["most_popular"]["image"]);
        $('#divTwo span a').text(data["most_popular"]["title"]);
        
        // most viewed
        $('#divThree .image_container img').attr('src', data["featured1"]["image"]);
        $('#divThree span a').text(data["featured1"]["title"]);

        // second most viewed
        $('#divFour .image_container img').attr('src', data["featured2"]["image"]);
        $('#divFour span a').text(data["featured2"]["title"]);
        
        // tell the article popup what you just set ...
        HomepageArticlePopup.set_article_ids({
			most_recommended : data["most_recommended"]["id"],
			most_popular     : data["most_popular"]["id"],
			featured1        : data["featured1"]["id"],
			featured2        : data["featured2"]["id"]
		});
    },
    
    // extract the default set from the DOM
    extract_default_article_set : function () {
        // grab the current article id set too
        var default_article_ids = HomepageArticlePopup.get_article_ids();
        return {
            "most_recommended" : {
                "id"    : default_article_ids["most_recommended"],
                "image" : HomepageImages._parse_css_url($('#divOne').css('background-image')),
                "title" : $('#divOne .orange_bg span').text(),
                "intro" : $('#divOne .trans_bg div').text()
            },
            "most_popular" : {
                "id"    : default_article_ids["most_popular"],
                "image" : $('#divTwo .image img').attr('src'),
                "title" : $('#divTwo span a').text()
            },
            "featured1" : {
                "id"    : default_article_ids["featured1"],
                "image" : $('#divThree .image_container img').attr('src'),
                "title" : $('#divThree span a').text()
            },
            "featured2" : {   
                "id"    : default_article_ids["featured2"],
                "image" : $('#divFour .image_container img').attr('src'),
                "title" : $('#divFour span a').text()
            }    
        };
    },
    
    // utils 
    _parse_css_url : function (url) {
        return url.substring(4, (url.length - 1));
    }
};

$(document).ready(function () { 

	// the get-a-quote and manage-your-stuff green boxes ...     
     
    var collapsable_forms = [ 'get_a_quote', 'manage_your_module', 'find_a_local_agent' ];
    
    var collapse_others = function (name) {
        for (var i = 0; i < collapsable_forms.length; i++) {
            if (name != collapsable_forms[i]) {
                $('#' + collapsable_forms[i] + '_open').hide();
                $('#' + collapsable_forms[i] + '_closed').show();                        
            }
        }
    };

    $('#get_a_quote_open > a:first').click(function () {
        $('#get_a_quote_open').slideUp('slow', function () {
            $('#get_a_quote_closed').show();
        });                          
    });
    $('#get_a_quote_closed > a:first').click(function () {
        $('#get_a_quote_closed').hide();        
        collapse_others('get_a_quote');                        
        $('#get_a_quote_open').slideDown('slow');
    });    
    
    $('#find_a_local_agent_open > a:first').click(function () {
        $('#find_a_local_agent_open').slideUp('slow', function () {
            $('#find_a_local_agent_closed').show();
        });               
    });
    $('#find_a_local_agent_closed > a:first').click(function () {
        $('#find_a_local_agent_closed').hide();
        collapse_others('find_a_local_agent');
        $('#find_a_local_agent_open').slideDown('slow');
    });
    
    $('#manage_your_module_open > a:first').click(function () {
        $('#manage_your_module_open').slideUp('slow', function () {
            $('#manage_your_module_closed').show();
        });               
    });
    $('#manage_your_module_closed > a:first').click(function () {
        $('#manage_your_module_closed').hide();
        collapse_others('manage_your_module');
        $('#manage_your_module_open').slideDown('slow');
    }); 
    
    // setup some of the UI blocking stuff ...
    
    $('.unblockButton').click( Homepage.hide_loading_screen ); 
    $('.blockOverlay').click( Homepage.hide_loading_screen );  
    
    // the customized-view-by-topic buttons
    
    var customized_topic = $("#container_right .customize_topic");
    
	$("ul li a img", customized_topic).bind('click', function() {	
		
		var curElem = $(this);
		
		$("ul li a img", customized_topic).each(function(i){
			var elem = $(this);
			if (curElem.attr('id') != elem.attr('id') && $(this).hasClass('rightActive')) {
				$(this).attr('src', PEPS.rollover.oldimage($(this).attr('src')));
				$(this).removeClass('rightActive');
			}
		});
	
		if ( !$(this).hasClass('rightActive') ) {
			HomepageImages.change_images( $(this).attr('id') );
		}
		
		$(this).addClass('rightActive');	
	});	
	 
});
