



var KiaUI = function()
{

    function onflashloaded() {
        $('object').each(function(){
            var that = this;
            // Code to fix Firefox Flash focus problem. (Codah 2009)
            // Append sibling flash container element to invalidate the 
            // Flash.
            if(window.navigator.appName == 'Netscape') {
                this.onmouseover = function() {
                    var parent = that.parentNode;
                    var span   = document.createElement('span');
                    parent.appendChild(span);
                    parent.removeChild(span);
                    that.focus();
                };
             }
        });  
    };
	

	// Fixes the News Display to page
	function _ND(selector, maxItems, pagingParentElement)
	{
		this.selector = selector;
		this.maxItems = maxItems;
		this.numPages = Math.ceil(this.selector.length / this.maxItems);
		this.page = 1;
		this.pageParent = pagingParentElement;
		
		this.init();
	}
	
		_ND.prototype.init = function()
		{
			this.drawPaging();
			this.drawItems();
		}
		
		_ND.prototype.drawPaging = function()
		{
			this.pageParent.append('<div class="paging"></div>')
			
			for(var i=1; i<=this.numPages; i++)
			{
				$('.paging').append('<a href="#" title="Click to view page ' + i + ' of Kia News">' + i + '</a>');
				
				$('.paging a:last').bind('click', {newsDisplay: this, page: i}, function(e)
				{
					return e.data.newsDisplay.gotoPage(e.data.page);
				})
			}
		}
		
		_ND.prototype.drawItems = function()
		{
			for(var i = 0, el; i<this.selector.length; i++)
			{
				el = this.selector[i];
				
				if(i < (this.page * this.maxItems) - this.maxItems 	||		i >= (this.page * this.maxItems))
				{
					$(el).css('display', 'none')
				}
				else
				{
					$(el).css('display', 'block');
				}
			}
			
			var pages = $('.paging a').removeClass('active');
			$('.paging a:nth-child(' + this.page + ')').addClass('active');
		}
		
		_ND.prototype.gotoPage = function(pageNumber)
		{
			if(pageNumber < 1 || pageNumber > this.numPages)
			{
				alert('Specified page number outside of range!');
			}
			else
			{
				this.page = pageNumber;
				this.drawItems();
			}
			
			return false;
		}
	
	
	//	Autoclear form field when user clicks in the field
	function _acff(selector)
	{
		this.selector 		= selector;
		this.defaultStr 	= this.selector.val();

		this.init();
	}
	
		_acff.prototype.init = function()
		{
			this.selector.bind('click', {searchUI: this}, this.clearText);
			this.selector.bind('blur', {searchUI: this}, this.restoreText);
		}
		
		_acff.prototype.clearText = function(e)
		{
			if(e.data.searchUI.selector.val() == e.data.searchUI.defaultStr)
			{
				e.data.searchUI.selector.val("");
			}
		}
		
		_acff.prototype.restoreText = function(e)
		{
			if(e.data.searchUI.selector.val() == "")
			{
				e.data.searchUI.selector.val(e.data.searchUI.defaultStr)
			}
		}
	
	function _addSep(selector, seperator)
	{
		this.selector = selector;
		this.seperator = seperator;
		this.selector.append(seperator);
	}
	
	// Create CSS class hooks for the sitemap
	function _smh(selector)
	{
		this.selector = selector;
		this.selector.children().children(':nth-child(1)').addClass('home');
		this.selector.children().children(':nth-child(2)').addClass('vehicle-root');
		// Make every 5th vehicle clear the rest to make a new row
		$('.vehicle-root > ul > li:nth-child(5)').css('clear', 'both');
		$('.vehicle-root > ul > li:nth-child(9)').css('clear', 'both');
		
		$('.vehicle-root li:last').addClass('last');
		
		// Add class names for the vehicles
		$('.vehicle-root > ul > li').each(function()
		{
			$(this).addClass( $(this).children('a').text().toLowerCase().replace(/ /, '-') );
		});
	}
	
	
	function _hs(selector)
	{
	    this.intervalDelay = 3000;
	    this.selector = selector;
	    this.controls;
	    this.next;
	    this.prev;
	    this.selectedIndex = 0;
	    this.selectedItem;
	    this.intervalID;
	    this.init();
	}
	
	    _hs.prototype.init = function()
	    {
		j = this.selector
		j.children('ul').addClass('js-enabled').children('li').hide()
		
		j.prepend('<div class="controls"></div>');
		
		
		this.controls = ctrls = this.selector.children('.controls');
		ctrls
		    .append('<a href="#" class="prev">&lt;</a>')
		    .append('<a href="#" class="next">&gt;</a>')
		
		prev = ctrls.children('.prev');
		    prev.bind('click', {that: this}, this.prevClickHandler);
		next = ctrls.children('.next');
		    next.bind('click', {that: this}, this.nextClickHandler);
		
		this.setItemAtIndex(this.selectedIndex, true);
		
		this.startAutoPlay();
	    }
	    
	    _hs.prototype.startAutoPlay = function()
	    {
		clearInterval(this.intervalID);
		this.intervalID = setInterval(function(scope)
		{
		    scope.next();
		    
		}, this.intervalDelay, this)
	    }
	    
	    _hs.prototype.nextClickHandler = function(e)
	    {
		e.preventDefault();
		var scope = e.data.that;
		scope.startAutoPlay();
		scope.next();
		return false;
	    }
	    
	    _hs.prototype.prevClickHandler = function(e)
	    {
		e.preventDefault();
		var scope = e.data.that;
		scope.startAutoPlay();
		scope.prev();
		return false;
	    }
	    
	    
	    _hs.prototype.next = function()
	    {
		var itemCount = this.selector.children('ul').children('li').length
		this.selectedIndex ++;
		
		if( this.selectedIndex >= itemCount)
		{
		    this.selectedIndex = 0;
		}
		
		this.setItemAtIndex(this.selectedIndex, true);
	    }
	    _hs.prototype.prev = function()
	    {
		var itemCount = this.selector.children('ul').children('li').length
		this.selectedIndex --;
		
		if(this.selectedIndex < 0)
		{
		    this.selectedIndex = itemCount - 1;
		}
		
		this.setItemAtIndex(this.selectedIndex, false);
	    }
	    
	    
	    _hs.prototype.setItemAtIndex = function(index, rightToLeft)
	    {
		if(this.selectedItem)
		{
		    w = this.selectedItem.parent().innerWidth();
		    this.selectedItem.animate({left: rightToLeft ? -w : w}, 500)
		}
		
		this.selectedItem = $(this.selector.children('ul').children('li')[index]);
		w = this.selectedItem.parent().innerWidth();
		
		this.selectedItem
		    .show()
		    .css('left', rightToLeft ? w : - w)
		    .animate({left: 0}, 500)
	    }
	
	
	function _subscribe(name, email, promotioncode)
	{
	    proxygen.subscriptionservice.SubscribeToConnectWithPromo(name, email, promotioncode, function(result){
        firstName = name.indexOf(' ') != -1 ? name.split(' ')[0] : name;
        message = "Thanks " + firstName + ", you're now subscribed to Kia Connect.";
        $("#subscribe-fields")
            .empty()
            .append('<p>' + message + '</p>');
      })
	}
	
	
	// return our namespace
	return {
		NewsDisplay		: _ND,
		HSlider			: _hs,
		AutoClearFormField	: _acff,
		AddSeperators 		: _addSep,
		OnFlashLoaded 		: onflashloaded,
		SiteMapHooks  		: _smh,
		SubscribeToConnect	: _subscribe
	}
}();


$(document).ready(function()
{
	// Upgrade the news UI.
	// !!! First, remove any empty paragraphs &/or links with no text nodes
	$('.news p:empty').remove();
	$('.news a:empty').parent().remove();
	$('p:empty', '.content').remove();
	news = new KiaUI.NewsDisplay($('.news p a'), 5, $('.news'));
	
	// Set up the slider for headlines
	hSlider = new KiaUI.HSlider($('.hslider'));
	
	// Upgrade the search UI.
	search	= new KiaUI.AutoClearFormField($('.txtsearch'));
	
	// Set up the subscribe control
  if($.validationEngine && $('#subscribe-fields').length > 0){
    $('form').validationEngine( {promptPosition : "centerRight", scroll: false} );
    $('form').validationEngine('attach')
    
        $('#subscribe-btn').click(function(e)
    {
        e.preventDefault();
        e.stopPropagation();
        
        var result = $('form').validationEngine('validate');
        if(result === true){
          KiaUI.SubscribeToConnect($('#first-name-input').val() + ' ' + $('#last-name-input').val(),
                  $('#email-input').val(),
                  $('#promo-input').val()
          );
        }
    })
  }
	

	
	
	// Add the bread crumbs seperators
	//breadcrumbs = new KiaUI.AddSeperators($('.breadcrumbs li:not(:last)'), '<span class="seperator">&gt;</span>');
	
	// Add some sitemap hooks for crappy browsers
	sitemapHooks = new KiaUI.SiteMapHooks($('.kiasitemap'));
	
	
});

