var timeout; // for timeout
var selectedImage;
var imgList; //List to preload Images	

$(document).ready(function (){ 
	
		//Preload Images
		$('[category]').each(function(){
  		imgList = this.getAttribute("hoversrc")+", "+ this.getAttribute("selectedsrc")+", " + this.getAttribute("offsrc");
  		//alert(imgList);
  		$.preloadImages(imgList);
  		});

		// Access the getlistings file for categories when a particular tab is clicked.
		// Get listings for love tab which shd appear by default when user loads the page
			
		var tabID = $("#sTab").val();
		
		if (tabID == ""){
		selectedImage = $("#tab1")[0]; 
		selectedImage.src = $("#tab1")[0].getAttribute('selectedsrc');;
		GetListings($('#tab1').attr("category")); 
		}
		else if ((tabID == "tab1") || (tabID == "tab2") || (tabID == "tab3") || (tabID == "tab4") || (tabID == "tab5")){
		selectedImage = $("#" + tabID)[0]; 
		selectedImage.src = $("#" + tabID)[0].getAttribute('selectedsrc');
		//GetListings($('#psychic-tab').attr("category")); 
		//GetListings($('#' + tabID).attr("category")); 
		GetListings($('#' + tabID).attr("category"));
		}
		else if (tabID != "tab5"){
				if (tabID != "tab4"){
		 			if (tabID != "tab3") {
						if (tabID != "tab2"){
							if(tabID != "tab1"){
							 if(tabID != ""){
			
							selectedImage = $("#tab1")[0]; 
							selectedImage.src = $("#tab1")[0].getAttribute('selectedsrc');;
							GetListings($('#tab1').attr("category")); 
							}}}}}}
		
		
		$('[category]').click(function() { // bind click event to the love tab
			//alert("tab selected, cat is "+ $(this).attr("category"));//debugging code
			clearTimeout(timeout);   
			GetListings($(this).attr("category"));
			return false;							
		});
		
		SetImageBehaviors();


});//close doc ready
			
function GetListings(category){

	$.ajax({
	url: '/documents/special_offers/getlistings.asp?tid=' + $("#tid").val() + '&cat=' + category + '&tlc=' + $("#tlc").val(),
	type: 'GET',
	dataType: 'xml',
	timeout: 5000,
	error: function(){
	getfListings();
	},
	success: function(xml){
		
	$('Listing',xml).each(function(i) {
		var count = jXML.getCount(xml,{"Listing":"Listing"});
      	//alert( count["Listing"]);
		if (count["Listing"] < 6) { getfListings();}
		//$("#fragment-2-container").empty();
		$("#fragment-1").show();
        listingTitle = $(this).find('title').text();
		listingImg = $(this).find('thumbNailImage').find('url').text();
		fullsizeImg = $(this).find('fullSizeImage').find('url').text();
		listingRate = $(this).find('rating').find('starsImage').find('url').text();
		listingName = $(this).find('memberName').text();
		listingmemUrl = $(this).find("memberUrl").text();
		listingUrl = $(this).find("expandedListingUrl").text();
		listingno = $(this).find('phoneNumber').find('number').text();
		listingextn = $(this).find('phoneNumber').find('extension').text();	
		listingsales = $(this).find('salesPitch').text();
					
		// the following statement is the clone of the div	
        newE1 = $("#list-template").clone().fadeIn("slow");

       	newE1.find('#listing-title').html(listingName);
		newE1.find('#listing-desc').html(listingTitle);
		newE1.find('#divfakelisting-img').html('<img src="'+listingImg+'" />');
		newE1.find('#divfakelisting-img-full').html('<img src="'+fullsizeImg+'" />');
		newE1.find('#fakelisting-profile').html('<a href="'+listingUrl+'" target="_blank">'+$("#profileText").val()+'</a>');
		newE1.find('#fakelisting-moreAdv').html('<a href="'+$("#morelink").val()+'" target="_blank">'+$("#moreText").val()+'</a>');
		newE1.find('#fakelisting-more').html('<a href="'+listingUrl+'" target="_blank">'+"Read More >>"+'</a>');
		newE1.find('#fakelisting-rating').html($("#ratingText").val() + '<img src="'+listingRate+'" width="60" height="13" alt="" border="0" />');
		newE1.find('#fakelisting-extn').html('ext. '+listingextn);
		newE1.find('#fakelisting-no').html(listingno);
		newE1.find('#fakelisting-sales').html(listingsales);			
			
		$("#listing"+i).empty(); // This empties the current cells and appends the dom with the newly created elements when user switches to another category
		newE1.appendTo("#listing"+i);
		});	//close each listing	
	}//close success
	});//close ajax function
	
	var delay = function() 
	{
	//alert("refreshing "+ this.category);
	GetListings(category);
	}	

	timeout = setTimeout(delay, 30000);
}//close GetListings function
//The getfListings functions is to get dummy listings when server is down or if the listings returned is less than the required number of listings.
function getfListings() {
	$("#fragment-2-container").fadeIn("slow");
	$("#fragment-2-container").show();
	$("#fragment-1").empty();

}
// The getCount function is to get the count of total listings in the xml
var jXML = {
    getCount: function(xml,nodes) {
        var response = {};
        for (var node in nodes) {
            response[node] = $(nodes[node],xml).length;
        }
        return response;
    }}

function SetImageBehaviors() {
		$('[category]').hover(SetHoverImage, RestoreImage);
		$('[category]').click(SetClickImage);
			if (selectedImage != null)
				$(selectedImage).unbind();	
		$('[category]').bind("click", (function() { // bind click event to the love tab
			//alert("love tab selected, cat is "+ $('#'+this.id).attr("category"));
			clearTimeout(timeout);   
			GetListings($('#'+this.id).attr("category"));
			return false;							
		}));
	}

		
function SetHoverImage() {
			this.src = 'http://i.keen.com/' + this.getAttribute('hoversrc');
		}
		
		function RestoreImage() {
			this.src = 'http://i.keen.com/' + this.getAttribute('offsrc');
		}
		
		function SetClickImage() {
			this.src = 'http://i.keen.com/' + this.getAttribute('selectedsrc');
			
			if (selectedImage != null)
				selectedImage.src = 'http://i.keen.com/' + selectedImage.getAttribute('offsrc');
			
			selectedImage = this;
			SetImageBehaviors();
		}
jQuery.preloadImages = function()
{
	for(var i = 0; i<arguments.length; i++)
	{
		jQuery("<img>").attr("src", arguments[i]);
	}
}






