// wiring up of these behaviors on page load requires jquery and a bunch of modules

	// function that loads the DoubleClick URL into the Iframe
	function trackClick(tag){
		if($('#trackingFrame')){
			var cacheBust = Math.floor(Math.random()*100000000000);
			url = 'http://fls.doubleclick.net/activityi;src=1392128;type=boscsp;cat=' + tag + ';ord=' + cacheBust;
			$('#trackingFrame').attr("src", url);
		}
	}

	$(document).ready(function() {

		// DART Tracking tags for metrics --------------------------------------
		$('.trackClick').click(function(myEvent){
			var tag = $(this).attr("id");
			trackClick(tag);
			return true;
		});

		// auto-deletable form input field
		$('.erasable').focus(function(){
			this.value = "";
			$(this).css({color: 'black'});
		});

		// lightbox links
		$('.fancybox').fancybox({
			type: "iframe",
			width: 760,
			height: 400
		});

		// embed flash movies
		$('.flashable').each(function(){
			element = $(this);
			movie = element.attr("swf:src");
			id = element.attr("id");
			params = {allowScriptAccess: "always"};
			swfobject.embedSWF(movie, id, element.outerWidth(), element.outerHeight(), "9.0.0", 'false', false, params);
		});
		$('.flashableWmode').each(function(){
			element = $(this);
			movie = element.attr("swf:src");
			id = element.attr("id");
			params = {wmode : "opaque", allowScriptAccess: "always"};
			swfobject.embedSWF(movie, id, element.outerWidth(), element.outerHeight(), "9.0.0", 'false', false, params);
		});
		$('.flashableTrans').each(function(){
			element = $(this);
			movie = element.attr("swf:src");
			id = element.attr("id");
			params = {wmode : "transparent",allowScriptAccess: "always"};
			swfobject.embedSWF(movie, id, element.outerWidth(), element.outerHeight(), "9.0.0", 'false', false, params);
		});

		// custom video player
		function createCustomPlayer(element, flashvars){
			flash = element.attr("swf:src");
			id = element.attr("id");
			params = {wmode : "opaque", allowScriptAccess: "always"};
			video = element.attr("swf:video");
			still = element.attr("swf:still");
			if(!flashvars){
				flashvars = {
					imgsrc: still,
					vidsrc: video};
			}

			swfobject.embedSWF(flash, id, element.outerWidth(), element.outerHeight(), "9.0.0", false, flashvars, params);
			
			var isIphone=navigator.userAgent.indexOf('iPhone')!=-1;
			if(isIphone){
				$('#'+id).html('<a href="/videos/watchvid?vid='+flashvars.vidsrc+'"><img src="'+flashvars.imgsrc.replace(".jpg","_play.jpg")+'"></a>');
			}
		}

		createCustomPlayer($('#customPlayer'));

		// custom video player playlist thumbnails
		// wiring up the links to use the Youtube javascript API to switch videos
        if($('.playCustomVideo')){
            $('.playCustomVideo').click( function(event){
                var video = $(this).attr("swf:video");
                var stillImage = $(this).attr("swf:still");

				// destroy old player
				if($('object#customPlayer')){
					$('object#customPlayer').parent().append('<div id="customPlayer" swf:src="/swf/video_player.swf" style="height:316px"></div>');
					$('object#customPlayer').remove();
				}
				createCustomPlayer($('#customPlayer'), {vidsrc:video,imgsrc:stillImage});
                
                // remove highlight from all other playlist items
				$('#playlist li').removeClass("nowPlaying");
                $(this).closest('#playlist li').addClass("nowPlaying"); // highlight the currently played video in the playlist

				// copy the title and description of the video thumbnail over to the player
				if(title = $(this).parents('.item').find('.videoText a:eq(0)')){
					$('#videoTitle').html(title.html());
				}
				if(desc = $(this).parents('.item').find('.description')){
					$('#videoDesc').html(desc.html());
				}

                event.preventDefault();
            });
        }
		
		// wire up the main nav dropdowns
		$('.nav li').hover(
			function(){
				$(this).find("ul.subNav").stop(true, true).slideDown('fast');
			},
			function(){
				$(this).find("ul.subNav").slideUp('fast');
			}
		);

	    $('.termsPopup').click( // wire up the popup link for the terms and conditions
            function(e){
                url = "http://www.bosch.us/content/language1/html/1062.htm?lang=en";
                window.open(url,"imprint","width=440,height=418,toolbar=no,location=no,directories=no,scrollbars=yes,status=no,menubar=no,resizable=no");
                e.preventDefault();
            }
        );

		// wire up the pulldowns for make / model / year

		// first, hide the model and year pulldowns
		//$('#carModel').css({"visibility": "hidden"});

		// replace regular pulldowns with custom styled pulldowns
		$("select.custom").selectbox({
			animationSpeed: "fast",
			listboxMaxSize: 18
		});

		$('#carMake').change(
			function(e){
				$.getJSON("/index/get-models", {make_id: $(this).val()}, function(response){
					var realSelect = $("#carModel");
					// check if the next pulldown is hidden, and if so, slide it in and show it later on
					var slideIn = false;
					if(!realSelect.is(":visible")){
						slideIn = true;
					}

					var shadowSelect = $("#carModel").parents('.jquery-selectbox');
					var options = '';
					var models = response.models;
					for (var i = 0; i < models.length; i++) {
						var bosch_model_name = models[i].model;
						model_name = models[i].model.replace("_", " ");
						options += '<option value="' + models[i].car_model_id + '" boschvalue="' + bosch_model_name + '">' + model_name + '</option>';
					}
					options = '<option value="">Model</option>' + options;
					shadowSelect.unselectbox(); // undo custom select so we can redoit with the new options

					realSelect.html(options);
					$('#carModel option:first').attr('selected', 'selected');
					realSelect.selectbox({
						animationSpeed: "fast"
					});
					realSelect.change(onModelChange);

					if(slideIn){

					}
				})
			}
		);

		var onModelChange = function(e){
			$.getJSON("/index/get-years", {model_id: $(this).val()}, function(response){
				var options = '';
				var years = response.years;
				for (var i = 0; i < years.length; i++) {
					options += '<option value="' + years[i].year + '">' + years[i].year + '</option>';
				}
				options = '<option value="">Year</option>' + options;
				$("#carYear").parents('.jquery-selectbox').unselectbox(); // undo custom select so we can redoit with the new options
				$("#carYear").html(options);
				$('#carYear option:first').attr('selected', 'selected');
				$("#carYear").selectbox({
					animationSpeed: "fast"
				});
			})
		}

		$('#carModel').change(onModelChange);

		// make the fancy button submit the parts search form
		$('#partsSearch').click(
			function(){
				form = $(this).parents('.partsFinder');
				form.submit();
			}
		);

		$('.partsFinder').submit(
			function(){
				$('#make').val( $('#carMake :selected').text());
				model = $('#carModel :selected').attr('boschvalue');
				$('#model').val( model ); // hidden field we will use to pass the real value to bosch
			}
		);

		// replace elements with custom scrollbars
		if( $('#playlist') ){
			$('#playlist').jScrollPane({
				showArrows:true, scrollbarWidth: 17,
				dragMinHeight:32, dragMaxHeight:32, animateInterval:50});
		}

		// auto-wire custom submit buttons inside forms
		$('.button a.submit').click(function(){
			$(this).parents('form').submit();
			return false;
		});

		// fade in/out functionality for the leaderboard layers
		var oldOne = $('#resultsSpeed');

		$('.switcherSpeed').click(function(){
			var newOne = $('#resultsSpeed');
			animateRanking(oldOne, newOne);
			oldOne = newOne;
			return false;
		});
		$('.switcherDistance').click(function(){
			var newOne = $('#resultsDistance');
			animateRanking(oldOne, newOne);
			oldOne = newOne;
			return false;
		});
		$('.switcherHorsepower').click(function(){
			var newOne = $('#resultsHorsepower');
			animateRanking(oldOne, newOne);
			oldOne = newOne;
			return false;
		});

		// animate one ranking pane out and another one in for the mini-ranking
		function animateRanking(outgoing, incoming){
			incoming.fadeIn(400).dequeue(); // instantly run the animation
			outgoing.fadeOut(200).dequeue();
		}

		// auto wire magic Ajax form
		$('form.ajaxForm').ajaxForm({success: showFormResponse});

		function showFormResponse(response){
			// remove all errors first
			$('.errors').remove();

			if(response.error){
				if(response.formErrors){
					var firstElement;
					var errorElements = [];
					for ( var i in response.formErrors ){
						var errorField = response.formErrors[i];
						var fieldId = '#' + errorField.field;
						if($(fieldId) && errorField.message){
							$error = $('<ul></ul>').addClass('errors').append(
									$('<li></li>').html(errorField.message)
								).css({display: 'none'});

							$(fieldId).after($error);

							// capture the first element with an error so we can go back and scroll to it later
							firstElement = firstElement ? firstElement : $(fieldId);
							errorElements.push( $(fieldId) );
						}
					}

					// show all the error elements
					$('.errors').each(
						function(){
							$(this).fadeIn();
						}
					);

					// scroll the page to the first error in the form and focus on it
					$('html,body').animate({scrollTop: firstElement.offset().top - 7}, 1000);
					firstElement.focus();
				}
			} else { // the form had no errors, lets proceed with submitting the video to youtube
				// set up the form action and hidden fields in the iframe form
				iframe = $('#videoUpload');
				innerForm = iframe.contents().find('#videoUploadForm');
				nexturl = "?nexturl=http://" + location.host + iframe.attr("src");
				innerForm.attr("action", response.target + nexturl);
				iframe.contents().find('#token').attr("value", response.token);

				// wire up the iframe with a callback for when YouTube responds
				iframe.load(function(){
					// now lets check whether the youtube response was successful
					url = iframe.contents().get(0).location;
					alert(url);
					//location = 'http://' + location.host + '/videos/upload-thank-you';
				});

				hasVideo = innerForm.find('input.file').attr("value");
				if(hasVideo){
					innerForm.submit();
				} else {
					alert(hasVideo + " You have to select a video to upload");
				}
			}
		}

	});