
jQuery(function($) {

var servereurl = 'http://www.cars911.com/hyundai/';
var carousel = servereurl + 'carousel/';
var make = 'Hyundai';
var salesPhone = '(866) 615-7580';
var servicePhone = '(866) 928-1639';
var partsPhone = '(800) 507-3286';
var prerollPlayed = '';
var vehicles = [];
vehicles[0] = {year: '2010', model: 'Accent', playlist: '0CD640CC20344872', instock: 1, active: false};
vehicles[1] = {year: '2011', model: 'Elantra', playlist: 'EF19738833747335', instock: 1, active: false};
vehicles[2] = {year: '2011', model: 'Elantra Touring', playlist: '232210F2C8CD3304', instock: 1, active: false};
vehicles[3] = {year: '2011', model: 'Sonata', playlist: '1C6205203EC9C9B1', instock: 1, active: true};
vehicles[4] = {year: '2011', model: 'Tucson', playlist: '9970B302865096EA', instock: 1, active: false};
vehicles[5] = {year: '2010', model: 'Santa Fe', playlist: '69BC3CDB6D2E78E0', instock: 1, active: false};
vehicles[6] = {year: '2011', model: 'Veracruz', playlist: '3822537D99BC2BD2', instock: 1, active: false};
vehicles[7] = {year: '2010', model: 'Genesis Coupe', playlist: 'A03C3246D273452E', instock: 1, active: false};
vehicles[8] = {year: '2011', model: 'Genesis', playlist: 'FBF9899FFEDB2016', instock: 1, active: false};
//vehicles[9] = {year: '2011', model: 'Equus', playlist: 'F73DD09F2AEBEEF3', instock: 1, active: false};

function vThumbnails(data) {
	jQuery('#thumbnails').addClass('loading');
	jQuery('#thumbnails #list li').remove();
	data = data.match(/#(.*)/);
	url = 'http://gdata.youtube.com/feeds/api/playlists/'+data[1]+'?v=2&alt=json-in-script&callback=?';
	jQuery.getJSON(url, function(json){
		var entries = json.feed.entry;
		jQuery.each(entries, function(i) {																						
			var title = entries[i].media$group.media$title.$t;
			var id = entries[i].media$group.yt$videoid.$t;
			jQuery('#thumbnails #list').append('<li><a href="api:'+ id +'"><div class="thumbnail"><span><img src="http://img.youtube.com/vi/'+ id +'/default.jpg"></span></div><div class="link">'+title+'</div></a></li>').show('fast', function () { jQuery('#video-container ul#list').animate({ opacity: 1 }, 1500 );
				jQuery('#thumbnails').removeClass('loading');																																																																								   			});
		});
	});
}

function bgImage(aVehicle) {
	jQuery('.image-preload').html('').addClass('loading');
	var img = new Image();
	jQuery(img).hide();
	jQuery(img).load(function () {
    	jQuery('.image-preload').removeClass('loading').append(this);
    	jQuery(this).fadeIn();
	}).attr('src', carousel+aVehicle+'-bg.jpg');
}

function preqaulifyLink(year, model) {
	jQuery('#engage-box .pre-qualified a').attr({ href: "FinancePreQualForm?vehicle:buy:year="+year+"&vehicle:buy:make="+make+"&vehicle:buy:model="+model});
}

function stockLink(stock, year, model) {
	if(stock==0){
		jQuery('#engage-box .pre-qualified, #engage-box .test-drive, #engage-box .inventory:eq(0)').hide();
		jQuery('#engage-box .inventory:eq(1)').show();
		jQuery('#engage-box .inventory:eq(1) a').attr({ href: year+model });
	} else if (stock==1){
		jQuery('#engage-box .inventory:eq(1)').hide();
		jQuery('#engage-box .pre-qualified, #engage-box .test-drive, #engage-box .inventory:eq(0)').show();
		jQuery('#engage-box .inventory:eq(0) a').attr({ href: "VehicleSearchResults?pageName=VehicleDetails&search=new&make="+make+"&model="+model+"&minYear="+year });
	} else {
		jQuery('#engage-box .pre-qualified, #engage-box .test-drive, #engage-box .inventory').show();		
		jQuery('#engage-box .inventory:eq(0) a').attr({ href: "VehicleSearchResults?pageName=VehicleDetails&search=new&make="+make+"&model="+model+"&minYear="+year });
		jQuery('#engage-box .inventory:eq(1) a').attr({ href: year+model });
	}
}

function currentTime(cue){
	var totalDuration = 23;
	var timeLeft = setInterval( totalDuration - cue, 1000);
	return timeLeft;
}

function displayPlayer ( h ){
	flowplayer('video', servereurl+"swf/flowplayer-3.2.5.swf", {
		playlist: [
				   { 
					   url: 'api:2ET4qNOKj0Q',

					   onStart: function(){
						   	this.getControls().show().enable({scrubber: false});
							this.getPlugin('background1').show();
					   		this.getPlugin('content').setHtml('<p>Video will begin next ...</p>');
							this.getPlugin("youtube").setPlaybackQuality('medium');
						},
					   onBeforePause: function() {return false;},
					   onFinish: function(){prerollPlayed = 1;}
				   },
				   {
					  url: h, 
					  onStart: function(){
						  this.getControls().show().enable({scrubber: true});
						  this.getPlugin('content').setHtml('');
						  this.getPlugin('background1').hide();
						  this.getPlugin("youtube").setPlaybackQuality('medium');
					  }
				   }
				   
				   ],
		plugins:  {
			controls: {
				url: servereurl+'swf/flowplayer.controls-3.2.3.swf',
				backgroundColor: "transparent",
				backgroundGradient: "none",
				sliderColor: '#FFFFFF',
				sliderBorder: '1.5px solid rgba(160,160,160,0.7)',
				volumeSliderColor: '#FFFFFF',
				volumeBorder: '1.5px solid rgba(160,160,160,0.7)',
				timeColor: '#ffffff',
				durationColor: '#535353',
				tooltipColor: 'rgba(255, 255, 255, 0.7)',
				tooltipTextColor: '#000000',
				display: 'none',
				zIndex: 5
			},
			content: {
				url: servereurl+'swf/flowplayer.content-3.2.0.swf',
				top: 0,
				left: 0,
				backgroundColor: 'transparent',
				backgroundGradient: 'none',
				border: 0,
				width: '100%',
				height: 45,
				opacity:1,
				zIndex: 3
			},
			background1: {
				url: servereurl+'swf/flowplayer.content-3.2.0.swf',
				top: 0,
				left: 0,
				backgroundColor: '#000',
				backgroundGradient: 'none',
				display: 'none',
				border: 0,
				width: '100%',
				height: 25,
				opacity:.7,
				zIndex: 1
			},
			background2: {
				url: servereurl+'swf/flowplayer.content-3.2.0.swf',
				bottom: 0,
				left: 0,
				backgroundGradient: 'none',
				border: 0,
				width: '100%',
				height: 45,
				opacity:0,
				zIndex: 2
			},
			youtube: {
				url: servereurl+'swf/flowplayer.youtube-3.2.1.swf'         
			}
		},
		clip: {
			autoPlay: true,
			provider: 'youtube',
			urlResolvers: 'youtube'
		}
	
	});
	if(prerollPlayed == 1){
		flowplayer('video').play(1);
	} else {
		flowplayer('video').play();
	}
}

function paneVideo(h) {
	$.getJSON("http://gdata.youtube.com/feeds/api/videos?q="+ h.substring(4) +"&alt=json-in-script&callback=?", function(data){
		var title = data.feed.entry[0].title.$t;
		var content = data.feed.entry[0].content.$t;
		jQuery("#video-pane h3").replaceWith('<h3>'+title+'</h3>');
		jQuery("#video-pane #info").replaceWith('<div id="info">'+content+'</div>');
	});
	displayPlayer(h);
}

function initLoadCarousel(a){
	var n = jQuery("#new-models .model").length;
	var modelLIwidth = jQuery("#new-models .model").width();
	var containerWidth = jQuery("#model-list").width();
	var modelULwidth = n * modelLIwidth;
	var scrollSpeed = 50;	
	var amount = modelLIwidth;
	var maxScroll = modelULwidth - containerWidth;
	maxScroll = '-' + maxScroll;
	jQuery("#new-models").css({ width: modelULwidth});
	var li = jQuery("#new-models .active").parent();
	var liIndex = li.parent().children().index( li );
	var position = jQuery("#new-models .active").parent().position();

	if(position.left < containerWidth){
		currentPos = 0;
		jQuery(".no-next").removeClass('no-next').addClass('next');
	} else if (position.left>maxScroll){
		currentPos = maxScroll;
		jQuery(".next").removeClass('next').addClass('no-next');
		jQuery(".no-prev").removeClass('no-prev').addClass('prev');
	} else {
		currentPos = '-'+position.left;	
		jQuery(".no-next").removeClass('no-next').addClass('next');
		jQuery(".no-prev").removeClass('no-prev').addClass('prev');
	}	

	jQuery("#new-models").css({left: currentPos});	
	vThumbnails(jQuery("#new-models .active").attr('href'));
	bgImage(a);
	preqaulifyLink(vehicles[liIndex].year, vehicles[liIndex].model);
	stockLink(vehicles[liIndex].instock, vehicles[liIndex].year, vehicles[liIndex].model);

	jQuery("#new-model-container .button a").click(function () {
		if (jQuery(this).is(".next") || jQuery(this).is(".no-next")) {
			currentPos = parseInt(jQuery('#new-models').css('left')) - amount;
			if ( currentPos >= maxScroll ){
				jQuery('#new-models').animate({ left: '-='+amount }, scrollSpeed );
			} else {
				currentPos = maxScroll;
			}
		} else {
			currentPos = parseInt(jQuery('#new-models').css('left')) + amount;
			if ( currentPos < 0 ){
				jQuery('#new-models').animate({ left: '+='+amount }, scrollSpeed );
			} else if ( currentPos == 0 ){
				currentPos = 0;
				jQuery('#new-models').animate({ left: '+='+amount }, scrollSpeed );
			}
		}
		
		if( currentPos >= 0 ){
			jQuery(".prev").removeClass('prev').addClass('no-prev');
			if( currentPos == 0 ){
				jQuery(".no-next").removeClass('no-next').addClass('next');
			}
		} else if( currentPos == maxScroll){
			jQuery(".next").removeClass('next').addClass('no-next');
			if( currentPos < 0 ){
				jQuery(".no-prev").removeClass('no-prev').addClass('prev');
			}
		} else {
			jQuery(".no-next").removeClass('no-next').addClass('next');
			jQuery(".no-prev").removeClass('no-prev').addClass('prev');
		}
		return false;
		
	});


}

function initLoadModles (){
	jQuery('#new-models li').remove();
	var activeClass = '';
	jQuery.each(vehicles, function(i) {	
		var vehicle = '<li class="model '+vehicles[i].model.replace(" ","-").toLowerCase()+'"><a ';
		if(vehicles[i].active){
			vehicle += 'class="active" ';
			activeClass = vehicles[i].model.replace(" ","-").toLowerCase();
		}
		vehicle +='title="'+vehicles[i].model+'" href="#'+vehicles[i].playlist+'">'+vehicles[i].model+'</a></li>';
		jQuery('#new-models').append(vehicle);
	});
	initLoadCarousel(activeClass);
}

if (jQuery(".carousel").length) {
	jQuery(".carousel").html('<div class="image-preload"></div><div id="info-container"><ul id="engage-box"><li class="pre-qualified"><a href="FinancePreQualForm"><span>Get<br/>Pre-qualified</span></a></li><li class="inventory"><a href="#"><span>Check<br/>Inventory</span></a></li><li class="inventory"><a href="#"><span>More<br/>Details</span></a></li><li class="hours-directions"><a href="HoursAndDirections"><span>Hours &amp;<br/>Directions</span></a></li><li class="test-drive"><a href="QuickQuoteForm"><span>Take it for a<br/>Test-drive</span></a></li><li class="contact-us"><a href="ContactUsForm"><span>Contact<br/>Us</span></a></li></ul><div id="video-container"><div id="thumbnails"><h3>Videos &amp; Reviews</h3><ul id="list"><li></li></ul></div><div id="video-pane"><div id="close"><a href="#">Close Panel</a></div><h3></h3><div id="video"><div></div></div><div id="info"></div></div></div><ul id="specials-box"><li></li></ul><div id="welcome-phone"><div id="welcome">Thank you for visiting<br />Glendale '+make+'!</div><div id="phonenumbers">Sales at '+salesPhone+'<br />Service at '+servicePhone+'<br />Parts at '+partsPhone+'</div></div></div><div id="new-model-container"><h3>'+make+' New Model Line-up</h3><div class="button"><a class="no-prev" href="#">previous</a></div><div id="model-list"><ul id="new-models"><li></li></ul></div><div class="button"><a class="next" href="#">next</a></div></div>');

	initLoadModles();
		
	jQuery('#new-model-container .model a').livequery(function(){	
		jQuery(this).bind('click', function() {
			if (!jQuery(this).is(".active")){
				var li = jQuery(this).parent();
				var ah = jQuery(this).attr('href');
				var liIndex = li.parent().children().index( li );
				jQuery('#new-model-container .model a.active').removeClass('active');
				jQuery(this).addClass('active');
				var activeVehicle = vehicles[liIndex].model.replace(" ","-").toLowerCase();
				if(jQuery('#video-pane').is('.open-pane')){
				jQuery("#video-pane").fadeOut(function(){
					jQuery("#video-container").stop().animate({ width: "268px"}, 500, function (){
						jQuery("#video-pane #video").html('<div></div>');
						jQuery('#video-pane').removeClass('open-pane');
					});
					bgImage(activeVehicle);
					vThumbnails(ah);
					preqaulifyLink(vehicles[liIndex].year, vehicles[liIndex].model);
					stockLink(vehicles[liIndex].instock, vehicles[liIndex].year, vehicles[liIndex].model);
				});	
				} else {
					jQuery("#video-container").animate({ width: "268px"}, 500 );
					bgImage(activeVehicle);
					vThumbnails(ah);
					preqaulifyLink(vehicles[liIndex].year, vehicles[liIndex].model);
					stockLink(vehicles[liIndex].instock, vehicles[liIndex].year, vehicles[liIndex].model);
				}
			}
			return false;
		});
	});
	
	jQuery('#video-pane #close a').livequery(function(){
		jQuery(this).click(function () {
			jQuery('#thumbnails li.active').removeClass('active');
			jQuery("#video-pane").fadeOut(function(){
				jQuery("#video-container").stop().animate({ width: "268px"}, 500 );
				jQuery("#video-pane #video").html('<div></div>');
			});
			jQuery('#video-pane').removeClass('open-pane');
			return false;
		});
	});
	
	jQuery('.carousel #thumbnails #list li a').livequery(function(){
		jQuery(this).bind('click', function() {
			var h = jQuery(this).attr('href');
			if (jQuery(this).parents('li').is(".active")) {
				jQuery('#thumbnails li.active').removeClass('active');
				jQuery("#video-pane").fadeOut(function(){
					jQuery("#video-container").stop().animate({ width: "268px"}, 500 );
					jQuery('#video-pane').removeClass('open-pane');
					jQuery("#video-pane #video").html('<div></div>');
				});
			} else if (!jQuery(this).parents('li').is(".active") && jQuery('#video-pane').is('.open-pane')) {
				jQuery('#thumbnails li.active').removeClass('active');
				jQuery(this).parents('li').addClass('active');
				paneVideo(h);
		   } else {
				jQuery('#video-pane').addClass('open-pane');
				jQuery(this).parents('li').addClass('active');
				jQuery("#video-container").stop().animate({ 
					width: "700px"}, 500, function (){
						jQuery("#video-pane").fadeIn();
						paneVideo(h);
				});
			}
		return false;
		});
	});


}

function slideSwitch( container, clicked ) {
	var activeS = jQuery(container+' div.active');
	var activeA = jQuery('.slideshow-links a.active');
	var nextS = activeS.next();
	var nextA = activeA.next();
	if( activeA.text() == jQuery(container+' .slide').length - 1 ){
		var nextS = jQuery(container+' .slide:eq(0)');
		var nextA = jQuery('.slideshow-links a:eq(0)');
		activeS.addClass('last-active');
	}
	if(clicked != false){
			var nextS = jQuery(container+' .slide:eq('+clicked.text()+')');
			var nextA = clicked;
			activeS.addClass('last-active');
	}
	
	nextA.addClass('active');
	activeA.removeClass('active');
	nextS.css({opacity: 0.0}).addClass('active').animate({opacity: 1.0}, 1000, function() {
            activeS.removeClass('active last-active');		
    });
}

function slideshow( container, links ){
if (jQuery(container+' .slide').length > 1) {
	  jQuery(container).append('<div class="slideshow-links"></div>');
	  jQuery(container+' .slide').each(function(index) {
		  if (index==0) {
			  jQuery(".slideshow-links").append('<a class="active" href="#">'+index+'</a>');
			  jQuery(this).addClass("active");
		  } else {
			  jQuery(".slideshow-links").append('<a href="#">'+index+'</a>');
		  }
	   });
	if (!links){jQuery(".slideshow-links").hide(); }
	setInt = setInterval(function(){slideSwitch( container, false )}, 5000);
} else {
	jQuery(container+' .slide').animate({opacity: 1.0}, 1000);
}

if (jQuery(".slideshow-links").length) {
	jQuery(".slideshow-links a").bind('click', function() {
		if (!jQuery(this).is('.active')) {
			if (!jQuery(container+' .slide').is(':animated')) {
				clearInterval(setInt);				
				slideSwitch( container, jQuery(this));
				setInt = setInterval(function(){slideSwitch( container, false)}, 5000);
			}
		}
		return false;
	});
}
}
slideshow('.slideshow', true );

jQuery("div.details-button a").click(function () {
  if (jQuery(this).is('.show')) {
	  jQuery(this).text('Hide Details');
	  jQuery(this).removeClass('show');
	  jQuery(this).parent().siblings('.details').css({display:'inline'});
  } else {
	  jQuery(this).text('Show Details');
	  jQuery(this).addClass('show');
	  jQuery(this).parent().siblings('.details').css({display:'none'});
  }
  return false;
});

jQuery(".top-specials a.details-button").click(function () {
  return false;
});

jQuery(".department-list a, .testimonial .staff a").click(function () {
	if (jQuery(this).parent().is('.name')) {
		pName = jQuery(this).text();
	} else {
		pName = jQuery(this).parent().siblings('.name').children().text();
	}
	var personInfo = '<iframe scrolling="no" frameborder="0" src="http://www.cars911.com/hyundai/employee.php?nm='+pName+'"></iframe>';
	jQuery.facebox(personInfo);
	return false;
});

//jQuery(".offer-links li a, .offers .left .image a").click(function () {
//	var special = jQuery(this).attr('rel');
//	var personInfo = '<div class="appointment"><iframe scrolling="no" frameborder="0" src="http://www.cars911.com/hyundai/service.php?special='+special+'"></iframe></div>';
//	jQuery.facebox(personInfo);
//	return false;
//});

$('#tabs-info ul li a').click(function(){ //When any link is clicked
	if(!jQuery(this).is(".active")){
	  $('#tabs-info ul .active').removeClass('active'); // Remove active class from all links
	  $(this).parent().addClass('active'); //Set clicked link class to active
	  var currentTab = $(this).attr('rel'); // Set variable currentTab to value of href attribute of clicked link
	  $('#tabs-info .tab').hide(); // Hide all divs
	  $("#tabs-info "+currentTab).show(); // Show div with id equal to variable currentTab 
	}
	return false;
});

jQuery('.thumbnail-container li a').bind('click', function() {
	var type = $(this).parents('.thumbnail-container').children('.header').children('span').html();
	jQuery('#pic-vid-gallery #full-size .inner').addClass('loading');
	if (type=='Photos') {
		var imagelink = $(this).attr('href');
		var img = new Image();
		jQuery(img).load(function () {
			jQuery(this).hide();
			jQuery('#pic-vid-gallery #full-size img, #pic-vid-gallery #full-size #obj').remove();
			jQuery('#pic-vid-gallery #full-size .inner').removeClass('loading').append(this);
			jQuery(this).fadeIn();
		}).attr('src', imagelink);
	} else {
		if(b[1].match(/6.0/)){
			jQuery.facebox(ie6());
		} else {
			var videolink = $(this).attr('rel');
			jQuery('#full-size .inner object').hide();
			jQuery('#pic-vid-gallery #full-size img, #pic-vid-gallery #full-size #obj').remove();
			jQuery('#full-size .inner').removeClass('loading').append(youtubeVideo(479,308,videolink));
			jQuery('#full-size object').fadeIn();
		}

	}
	return false;
});

if (jQuery(".popup-question form").length) {
    jQuery(".popup-question form").validate({
		rules: {
			frm_nm: "required",
			frm_eml: {
				required: true,
				email: true
			},
			frm_qa: "required",
			empolyee_nm: "required",
			empolyee_eml: "required",
			dlr: "required"
		},
		messages: {
			frm_nm: "Please enter your name",
			frm_eml: "Please enter a valid email",
			frm_qa: "Please enter your question",
			empolyee_nm: "",
			empolyee_eml: "",
			dlr: ""
		},
		submitHandler: function() {
			jQuery('.popup-question form').hide();
			jQuery('.popup-question').addClass('loading');
			ajaxStringData = $('.popup-question form').serialize();
			jQuery.ajax({
   			type: "POST",
   			url: "http://www.cars911.com/hyundai/email.php",
   			data: ajaxStringData,
   			success: function(){
				jQuery('.popup-question form').remove();
				jQuery('.popup-question').removeClass('loading').append('<div class="confirm-message">Thank you, I will contact you shortly</div>');
  				}
			});
		}
	});
}
  
if (jQuery(".service-form form").length) {
	jQuery(".service-form form").validate({
		rules: {
			'vehicle:buy:year': "required",
			'vehicle:buy:make': "required",
			'vehicle:buy:model': "required",
			'service:preferred_day': "required",
			'service:preferred_time': "required",
			'service:alternate_day': "required",
			'service:alternate_time': "required",
			'contact:name:first': "required",
			'contact:name:last': "required",
			'contact:email': {
				required: true,
				email: true
			},
			'contact:phone:phone:day': "required",
			'preferred_contact': "required",
			'contact:address:home:postalcode': "required"
		},
		messages: {
			'vehicle:buy:year': "",
			'vehicle:buy:make': "",
			'vehicle:buy:model': "",
			'service:preferred_day': "",
			'service:preferred_time': "",
			'service:alternate_day': "",
			'service:alternate_time': "",
			'contact:name:first': "",
			'contact:name:last': "",
			'contact:email': "",
			'contact:phone:phone:day': "",
			'preferred_contact': "",
			'contact:address:home:postalcode': ""
		},
		submitHandler: function() {
			jQuery('.service-form form').hide();
			jQuery('.service-form').addClass('loading');
			ajaxStringData = $('.service-form form').serialize();
			jQuery.ajax({
   			type: "POST",
   			url: "http://www.cars911.com/hyundai/process.php",
   			data: ajaxStringData,
   			success: function(){
				jQuery('.service-form form').remove();
				jQuery('.service-form').removeClass('loading').append('<div id="confirm-message" class="confirm-message">Thank you, We will send you a confirmation shortly</div>');
  				}
			});
		}
	});
}

if (jQuery(".newsletter-form form").length) {
   	jQuery(".newsletter-form form").validate({
		rules: {
			'frm_nm': "required",
			'frm_eml': {
				required: true,
				email: true
			}
		},
		messages: {
			'frm_nm': "",
			'frm_eml': ""
		},
		submitHandler: function() {
			jQuery('.newsletter-form form').hide();
			jQuery('.newsletter-form').addClass('loading');
			ajaxStringData = $('.newsletter-form form').serialize();
			jQuery.ajax({
   			type: "POST",
   			url: "http://www.cars911.com/hyundai/nl-process.php",
   			data: ajaxStringData,
   			success: function(){
				jQuery('.newsletter-form form').remove();
				jQuery('.newsletter-form').removeClass('loading').append('<div id="confirm-message" class="confirm-message">Thank you, We will send you a confirmation shortly</div>');
  				}
			});
		}
	});
}


});
