YAHOO.namespace("ps.Showcase");
(function () {
    var Dom = YAHOO.util.Dom,
    	Ev  = YAHOO.util.Event,
    	Sh  = YAHOO.ps.Showcase;

    var config = { rotate: 5,
    			   url: '',
    			   trackDb: 0,
    			   trackGoogle: '' };
	
	var setConfig = function (keys) {
		for(var i in keys) {
			if (YAHOO.lang.hasOwnProperty(keys, i)) {
				config[i] = keys[i];
			}
		}
	};
	
	var listings,
		count,
		current,
		timeout,
		trackCurr,
		total;
	
	var addListings = function (showListings) {
		listings  = showListings;
		count     = listings.length;
		current   = 0;
		trackCurr = 0;
		total     = 0;
	};
	
	var load = function (num) {
		// Cancel rotation
		window.clearTimeout(timeout);
		// Change the current listing to the number provided
		// then remove old image and load new
		current = num;
		removeOld();
	};
	
	var next = function () {
		// Set the current position
		current++;
		total++;
		if (current >= count) {
			current = 0;
		} 
		if (total < count*4) {
			// Remove old image and load new
			removeOld();
		}
    };
    
    var removeOld = function () {
    	Dom.addClass('navigation', 'hide');
		var animImage = fadeOut('image', 1);
		var animTitle = fadeOut('title', 0.7);
		animImage.onComplete.subscribe(function() {
			loadCurrent();
		}); 
		animImage.animate();
		animTitle.animate();  
    };
	
	var loadCurrent = function () {
		var listing = listings[current];
		loadImage(listing['id']);
		
		// Create image
		var html = '<img src="' + config['url'] + '/' + listing['id'] + '/_featured.jpg" alt="Featured Real Estate Listing - ' + 
			       listing['street_address'] + ', ' + listing['city'] + ', ' + listing['state'] + ' ' + listing['zip'] + '" />';
		// Add title or address and price
		var title = listing['title']
		if (title == '') {
			title = listing['street_address'] + ', ' + listing['city'] + ', ' + listing['state'] +  ', ' +
					listing['zip'] + ' - $' + addComma(listing['list_price']);
		}
		
		document.getElementById('image').innerHTML = html;
		document.getElementById('title').innerHTML = title;
		
		// Make sure 'image' div  listener is cleared and setup the new link
		YAHOO.util.Event.removeListener('image', 'click');
    	YAHOO.util.Event.addListener('image', 'click', function(){
    		// Cancel rotation before loading listing
    		window.clearTimeout(timeout);
    		location.href = '/realestate/listing/key/' + listing['listing_key'];
    	});

    	if (config['trackDb']) {
    		// Send back AJAX request will tracking details
    		track(listing['listing_key']);
    	}

    	// Track listing display if google tracking is active and the ini is set with the path
    	// Also make sure everything is only counted once per page load
    	if (pageTracker && config['trackGoogle'] != '' && trackCurr <= count) {
			pageTracker._trackPageview(config['trackGoogle'] + '/' + listing['listing_key'] + '/showcase');
		} 

		changeNavigation();
		// Fade image in
		var animImage = fadeIn('image', 1);
		var animTitle = fadeIn('title', 0.7);
		animImage.onComplete.subscribe(function() {
	    	Dom.removeClass('navigation', 'hide');
			timeout = window.setTimeout("YAHOO.ps.Showcase.next();", (config['rotate']*1000));
		}); 
		animImage.animate();
		animTitle.animate();
    };
    
    var trackSuccess = function (o) {	
    };
    
    var track = function (key) {
    	// Only track listings once each page load
    	trackCurr++;
    	if (trackCurr <= count) {
	    	var callback = { success:trackSuccess };
	    	var postData = "key=" + key;
	
	        YAHOO.util.Connect.asyncRequest('POST', '/server/index/showcase', callback, postData); 
    	}
    };
    
    var addComma = function (num) {
		num += '';
		x = num.split('.');
		x1 = x[0];
		x2 = x.length > 1 ? '.' + x[1] : '';
		var rgx = /(\d+)(\d{3})/;
		while (rgx.test(x1)) {
			x1 = x1.replace(rgx, '$1' + ',' + '$2');
		}
		return x1 + x2;
	};
    
    var loadImage = function (featuredId) {
		featImage = new Image(); 
		featImage.src = "/resources/live/featured/" + featuredId + "/_featured.jpg";
    };
	
	var fadeIn = function (id, maxOpacity) {
		// If opacity is undefined or browser is ie set to 1
		if (YAHOO.lang.isUndefined(maxOpacity)) {
			maxOpacity = 1;
		}
		
		Dom.setStyle(id, 'opacity', '0'); 
		return new YAHOO.util.Anim(id, { opacity: { to: maxOpacity }}, 1, YAHOO.util.Easing.easeIn);
	};
	
	var fadeOut = function (id, maxOpacity) {
		// If opacity is undefined or browser is ie set to 1
		if (YAHOO.lang.isUndefined(maxOpacity)) {
			maxOpacity = 1;
		}
		
		Dom.setStyle(id, 'opacity', maxOpacity);
		return new YAHOO.util.Anim(id, { opacity: { to: 0 }}, 1, YAHOO.util.Easing.easeOut);
	};
	
	var initNavigation = function () {
		var navTags = '';
        for(var i=0; i<count; i++) {
        	navTags += '<span id="nav' + i + '" onclick="YAHOO.ps.Showcase.load(' + i + 
        			   ');" class="nav">' + (i+1) + '</span>';
        }
        document.getElementById('navigation').innerHTML = navTags;
	};
	
	var changeNavigation = function () {
		childEl = Dom.getElementsByClassName('nav', 'span', 'navigation');
		Dom.removeClass(childEl, 'active');
		Dom.addClass('nav' + current, 'active');
	};
    
    Ev.onDOMReady(function () {
    	initNavigation();
    	loadCurrent();
    });

    // Public functions
    Sh.setConfig   = setConfig;
    Sh.addListings = addListings;
    Sh.load		   = load;
    Sh.next		   = next;
})();    
