function include(filename) {
	var head = document.getElementsByTagName('head')[0];
	script = document.createElement('script');
	script.src = filename;
	script.type = 'text/javascript';
	head.appendChild(script)
}

/*
function checkCountry() {
    var country = readCookie('country');
    //debug.log("Cookie country = " + country);    
    if (country == 'unknown') {
        Shadowbox.open({
            content: url='/location/choose',
            player: "iframe",
            title: "Choose your country",
            height: 350,
            width: 350
        })
    }
}
*/

function createCookie(name,value,days) {
	if (days) {
		var date = new Date();
		date.setTime(date.getTime()+(days*24*60*60*1000));
		var expires = "; expires="+date.toGMTString();
	}
	else var expires = "";
	document.cookie = name+"="+value+expires+"; path=/";
}

function readCookie(name) {
	var nameEQ = name + "=";
	var ca = document.cookie.split(';');
	for(var i=0;i < ca.length;i++) {
		var c = ca[i];
		while (c.charAt(0)==' ') c = c.substring(1,c.length);
		if (c.indexOf(nameEQ) == 0) return c.substring(nameEQ.length,c.length);
	}
	return null;
}

function eraseCookie(name) {
	createCookie(name,"",-1);
}

/*
 * Generic window opening function
 */
function openWin(url, name, opts) {
    document.domain = 'teslamotors.com';
    if (!opts) {
        opts = "";
    }
    return window.open(url, name, opts);
}

/*
 * Activate any hover tooltips (used on Technology page, and Featured owner photostrips)
 */
function activateHovers() {
    
    /* Technology page hovers */
    if ($('.hover_body').length) {
        $('.hover_body').hide();
        $('#hover_body_instructions').show();
        $('.hover_tooltip').hide();
        $('.hover_tooltip').hoverIntent(
            function() {
                // get id and show the corresponding body
                var my_id = $(this).attr('id');
                my_id = my_id.split('_')[2];
                $(this).find('.content').stop().fadeIn();
                $('#hover_component_' + my_id).stop().fadeIn(); // highlight on car
                // IE don't support opacity with PNGs            
                if($.support.opacity) {
                    $('#hover_body_' + my_id).stop().fadeIn(); // caption                
                    $('#hover_body_instructions').stop().fadeOut();            
                } else {
                    $('#hover_body_' + my_id).stop().show(); // caption                                
                    $('#hover_body_instructions').hide();            
                }
            },
            function() {
                // get id and show the corresponding body
                var my_id = $(this).attr('id');
                my_id = my_id.split('_')[2];
                $(this).find('.content').fadeOut();
                $('#hover_component_' + my_id).fadeOut();            
                // IE don't support opacity with PNGs
                if ($.support.opacity) {
                    $('#hover_body_' + my_id).fadeOut();                
                    $('#hover_body_instructions').stop().fadeIn(); 
                } else {
                    $('#hover_body_' + my_id).hide();                                
                    $('#hover_body_instructions').show();
                }
            }
        );
    }
    
    /* Featured owner photostrip hovers */
    if ($('div.view-featured-owners-nq').length) {
        $('div.view-featured-owners-nq div.views-field-field-photo-fid img').mouseenter(
            function() {
                $('#clone', $(this).parents()).remove(); //gc
                var owner = $(this).parents('div.views-row');
                var pos = getOrdinalPosition(owner);
                var x_offset = pos * 75;
                // clone the div as a popup
                var clone = owner.clone();
                clone.addClass('hovered');
                clone.attr('id','clone');
                clone.css('left', x_offset);
                clone.mouseout(function() {
                    $(this).remove();                            
                });
                clone.appendTo('#featured-owners .view-content');
            });
    }
    
}


/*
 * Initialize store page photo galleries
 */
function initGalleries() {
    if (window.Galleria && Drupal.settings.tesla.flickr_api_key) {
	    Galleria.loadTheme('/sites/all/themes/tesla/js/galleria/src/themes/classic/galleria.classic.js');
        var flickr = new Galleria.Flickr(Drupal.settings.tesla.flickr_api_key); // initialize the plugin
    	
        $('#gallery-index li a').click(function() {
            $('#gallery-index li').removeClass('selected');
            $(this).parent().addClass('selected');
    		var href = $(this).attr('href').split('=');
    		var set_id = href[1];
    		flickr.getSet(set_id, {size:'medium'}, function(data) {
    			$('#galleria').galleria({
    		        data_source: data
    		    });
    		})
    		return false;
        });

        // trigger click on first gallery item
        $('#gallery-index li.first a').trigger('click');        
    }
}

// delay-remove fade status messages (from e.g. region picker)
function fadeAlerts () {
    $('.messages.fade').fadeOut(400);
    
}

// given an element, figure out which oridinal position it has
// among its siblings
function getOrdinalPosition(el) {
    var position = -1;
    // we have to do this because el.siblings() does not return the element itself
    var siblings = el.parent().children(); 
    $.each(siblings, function(key, value) {
	if (value == el[0]) {
	    position = key;
	    return false;
	}
    });
    return position;
}




/*
 * Initialize analytics custom events
 */
function initAnalyticsEvents() {
    $('.page-own a#request-callback').click(function() {
        debug.log("Track pageview for /own/callback_form")
       _gaq.push(['_trackPageview', '/own/callback_form']);
    });

    $('body#page-goelectric-incentives a#request-callback').click(function() {
        debug.log("Track pageview for /incentives/callback_form")
       _gaq.push(['_trackPageview', '/incentives/callback_form']);
    });

    $('#store-body a.schedule-button').click(function() {
        debug.log("Track pageview for /store/appointment_form")
       _gaq.push(['_trackPageview', '/store/appointment_form']);
    });

    $('#store-body a.callback-button').click(function() {
        debug.log("Track pageview for /store/callback_form")
       _gaq.push(['_trackPageview', '/store/callback_form']);
    });

    $('body#page-goelectric #hero-action .replace-text').click(function() {
        debug.log("Track pageview for /video/goelectric_v1")
       _gaq.push(['_trackPageview', '/video/goelectric_v1']);
    });

    if ($('body#page-roadster').length) {
        // Buy button in Roadster page slider
        $('#page-roadster #buy .button a').click(function() {
            debug.log("Track pageview for /roadster/buy_click")
           _gaq.push(['_trackPageview', '/roadster/buy_click']);
        });

        // Appt button in Roadster page slider
        $('#page-roadster #drive .button a').click(function() {
            debug.log("Track pageview for /roadster/appt_click")
           _gaq.push(['_trackPageview', '/roadster/appt_click']);
        });
        
        // Roadster experience video
        $('#page-roadster #experience .overlay a').click(function() {
            debug.log("Track pageview for /video/roadster/experience_v1")
           _gaq.push(['_trackPageview', '/video/roadster/experience_v1']);
        });    

        // Roadster interior video
        $('#page-roadster #vision .overlay a').click(function() {
            debug.log("Track pageview for /video/roadster/interior_v1")
           _gaq.push(['_trackPageview', '/video/roadster/interior_v1']);
        });
        
    }

    if ($('body#page-models').length) {
        // Reserve button in Model S page slider
        $('#page-models #reserve .button a').click(function() {
            debug.log("Track pageview for /models/reserve_click")
           _gaq.push(['_trackPageview', '/models/reserve_click']);
        });

        // Discuss button in Model S page slider
        $('#page-models #discuss .button a').click(function() {
            debug.log("Track pageview for /models/discuss_click")
           _gaq.push(['_trackPageview', '/models/discuss_click']);
        });    
        
        // Model S video
        $('#page-models #experience .overlay a').click(function() {
            debug.log("Track pageview for /video/models/thefuture_v1")
           _gaq.push(['_trackPageview', '/video/models/thefuture_v1']);
        });        
        
    }    

}    

/*
 * attach analytics events for webform submits
 */
function attachWebformAnalytics(form_id) {
    switch (form_id) {
        case 'webform-client-form-119':
            // own/store/incentives call me back
            // Same form id is used on both store, own and incentives callback forms
            // need to figure out which one it is
            if ($('body').hasClass('node-type-teslastore')) {
                debug.log('Track pageview for store/callback_submit');
                _gaq.push(['_trackPageview', '/store/callback_submit']);                            
            } else if ($('body').attr('id')=='page-goelectric-incentives') {
                debug.log('Track pageview for incentives/callback_submit');
                _gaq.push(['_trackPageview', '/incentives/callback_submit']);                                        
            } else {
                debug.log('Track pageview for own/callback_submit');
                _gaq.push(['_trackPageview', '/own/callback_submit']);                            
            }
            break;
        case 'webform-client-form-3836':
            // test drive
            debug.log('Track pageview for testdrive_submit');
            _gaq.push(['_trackPageview', 'testdrive_submit']);            
            break;
        case 'webform-client-form-120':
            // store appt form
            debug.log('Track pageview for /store/appointment_submit');
            _gaq.push(['_trackPageview', '/store/appointment_submit']);            
            break;
        case 'webform-client-form-121':
            // store appt form
            debug.log('Track pageview for /event_submit');
            _gaq.push(['_trackPageview', '/event_submit']);            
            break;            
        case 'webform-client-form-3974':
            // Newsletter signup
            debug.log('Track pageview for /newsletter_submit');
            _gaq.push(['_trackPageview', '/newsletter_submit']);            
            break;
        case 'webform-client-form-122':
            // Newsletter signup (US)
            debug.log('Track pageview for /newsletter_us_submit');
            _gaq.push(['_trackPageview', '/newsletter_us_submit']);            
            break;
    }
}    

/*
 * Make an anchor open in a new window
 */
function openLinkNewWindow(link) {
    if (link.length) {
        link.click(function() {
            openWin(link.attr('href'));
            return false;
        });                  
    }
}

/*
 * Perform any locale-specific tasks
 */
function attachLocaleHandlers() {
    // look for country/language code in body class. It will look something like 'i18n-ja_JP'
    var body_classes = $('body').attr('class').split(' ');
    var code = '';
    for (var i=0, l=body_classes.length; i<l; i++) {
        if (body_classes[i].indexOf('i18n') > -1) {
            code = body_classes[i].substr(5);
        }
    }
    switch(code) {
        case 'ja_JP':
            // for Japan, open IR and careers links in a new window
	    openLinkNewWindow($('.menu-17808 a'));
	    openLinkNewWindow($('.menu-17807 a'));
	    openLinkNewWindow($('ul.quicklinks li:first-child a'));
	    // Change labels of form fields on own page to EN
            if ($('#tesla-buy-basic-form').length) {
	        $('#edit-Email-wrapper label').html('EMAIL:');
	        $('#edit-Country-wrapper label').html('COUNTRY:')
	    }
            break;
    }
}


/*
 * Initialize home page heros and newsletter signup
 */
function initHome() {
    if ($('body').attr('id') == 'page-homepage') {
        // hero centered, absolutely
        //reposHero();
        //var resizeTimer = null;
        //$(window).resize(function() {
        //    reposHero();
        //});
    
        var homepageSlideshowOptions = {
            timeout: 6500, 
            fx: "fade", 
            speed: 700, 
            delay: 7000, 
            vss_id: "homepage_slideshow-default", 
            sort: 1, 
            start_paused: 0, 
            sync: 1, 
            random: 0, 
            pause: 0, 
            nowrap: 0,
            cleartype: true, 
            cleartypenobg: false,
            pager: "#hero-thumbs", 
            activePagerClass: "activeSlide",
            pagerAnchorBuilder: function(idx, slide) {
                var thumb = $('.slideshow-controls > li').eq(idx);
                $(thumb).filter('li').addClass('pager-item');
                $(thumb).children('img').wrap('<a href="#" />');
                return thumb;
            }
        };
        $('#hero-image').cycle(homepageSlideshowOptions);

        /* -- Newsletter Form -- */
        var $signupForm = $("#newsletter-signup form");
    
        $signupForm.ajaxError(function() { $(this).replaceWith('<p>Thank you for signing up. Watch your inbox for the next edition of the Tesla Newsletter.</p>'); }); //intended for static HP only
    
        // fancy label
        var signupLabel = $('#edit-submitted-email-wrapper label').hide().text();
        if (signupLabel !== '') {
            $('#edit-submitted-email').val(signupLabel.match(/^([\w\s]+)/)[1]).click(function() {
                this.value='';
                $(this).unbind('click');
            });
        }
            // progress bar
            //$signupForm.submit(function() {
            //        $(this).find('input[type=submit]').hide()
            //        .after('<img class="ajax-loader" src="/sites/all/themes/tesla/images/ajax-loader-bar.gif" alt="Loading, please wait" />');
            //});
    
        // ensure form uniqueness
        //var sF_nid = 3974;
        //$.get('webform/'+ sF_nid, function(data) { 
        //	$signupForm.find('input[name=form_build_id]')
        //		.replaceWith($(data).find('input[name=form_build_id]'));
    
        //	$signupForm.find('input[name=form_token]')
        //		.replaceWith($(data).find('input[name=form_token]'));
        //});

    }
}


/*
 * Pass in an array of image urls to pre-load
 */
Drupal.settings.imagecache = [];
function preLoadImages() {
    var args_len = arguments.length;
    for (var i = args_len; i--;) {
      var cacheImage = document.createElement('img');
      cacheImage.src = arguments[i];
      Drupal.settings.imagecache.push(cacheImage);
    }
}


/* If height of body is less than height of window, move footer to bottom 
 * so it's not sitting in the middle of the page.
 */
function repositionFooter() {
    var window_height = $(window).height();
    var body_height = $('body').height();
    var page_height = $('#page').height();
    var footer_height = $('#footer').height() + 10; // $('#footer').height() will say 58 but it's really 68 because of bottom margin
    var difference = window_height - page_height;
    if (difference > 0) {
        // reposition footer to bottom if we're on a page with short content and the window is tall
        // Check that the content height is at minimum 360 so we don't readjust the footer in the case
        // that page_height is being incorrectly reported due to an unclosed div or something
        if (page_height > 360) {            
            var offset = difference - footer_height;            
            $('#footer').css('top', offset + 'px');            
        }
    } else {
        // This closes up any little gaps at the bottom in the case where the content is longer than the window 
        // Usually just in IE
        // page_height + footer_height should = body_height
        var gap = body_height - page_height;
        if (gap > 0) {
            $('#footer').css('top', gap + 'px');            
        }
    }
    $('#footer').show();
}

Drupal.Ajax.plugins.shadowbox = function(hook, args) {
    if (hook === 'init') {
	$('form.webform-client-form').after('<div class="submit-progress"><img src="/sites/all/themes/tesla/images/ajax-loader-bar.gif" alt="Sending, please wait" /></div>');
	//unbind ajax form handlers from original 
	function ajaxUnbindOriginal(sbInline) { 
	    var f;
	    if (f = $('.ajax-form', sbInline.content)) {
		$("#"+f.attr('id'), document).each(function() {
		    $(this).unbind('submit')
		    .find('input[type=submit]').unbind('click');
		});
	    }
	};
	// and re-bind in SB context
        function ajaxShadowbox(sbInline) {
            Drupal.attachBehaviors($('#sb-player'));
        }

        Shadowbox.options['onFinish'] = ajaxShadowbox;
        Shadowbox.options['onOpen'] = ajaxUnbindOriginal;

	    //disable keyboard overrides
        Shadowbox.options['enableKeys'] = false;

	return false;
    }
    else if (hook === 'submit') {
        debug.log('shadowbox hook submit');
        var thisForm = args.submitter.parents('form.webform-client-form');        
        args.submitter.hide();
        thisForm.next('.submit-progress').show();
        attachWebformAnalytics(thisForm.attr('id'));
        
    }
    else if (hook === 'afterMessage') {
        if (args.status == false) {
            $('.submit-progress').hide();
            args.local.submitter.show();
        }

        
    }
    else if (hook === 'redirect') {
        
        if (args.status === true) {
            $.get(args.redirect, function (data) {
                var confMsg = $(data).find('.webform-confirmation');
                $('.submit-progress').hide();
                args.local.form.parents('.node-webform').html(confMsg);
            });
        }
	return false; //do not redirect
    }
    // there is no 'error' hook... condition logged to console, and the form seems to hang
    //else if (hook === 'error') {
    //    $('.submit-progress').hide();
    //    thisForm.replaceWith('<div class="webform-confirmation error">Sorry, there was an internal server error while submitting this form. Please try again later.</div>'); 
    //}
    return true;
}

/*
 * Do this stuff as soon as DOM is ready.
 */
$(document).ready(function() {
    
    if (typeof Drupal.settings.tesla == 'undefined') { Drupal.settings.tesla = new Object(); }
    // Store galleries
    initGalleries();

    // Typekit
    // If any Galleries are on the page, need to delay loading typekit until after galleries are
    // initialized, or else Galleries don't work in IE
    if (window.Galleria && Drupal.settings.tesla.flickr_api_key && $.browser.msie) {
        setTimeout('initTypeKit();', 700); 
    } else {
        initTypeKit();
    }

    /**
     * main menu: secondary nav hovers
     */
    $('#site-menu .main-menu > li').not('.active-trail, .home').hoverIntent(
        function() {
            var $this_menu = $('> ul', this);
            var full_height = 0;
            clearTimeout(this.willHide);
            $(this).addClass('activeHover');
            $this_menu.children('li').each(function() {
                full_height += parseInt($(this).height());
            });
            $this_menu.animate({'height':full_height}, 200)
            .parent().siblings('li').removeClass('activeHover').children('ul').css({height: 0});
                // Ensure this is the only menu showing 
        },
        function() {
            var curItem = this;
            this.willHide = setTimeout(function () {
                $('> ul', curItem).animate({height: 0}, 200, function () {
                    $(curItem).removeClass('activeHover');
                });
            }, 999);
        } );

    // hook-up footer animation
    $('#footermap').hoverIntent(
            function() { 
                $('#footermap li ul li').slideDown("slow");     
            },
            function() {
                // do nothing
            });

    // find any hover tooltips and activate them
    activateHovers();

    // hook google analytics events
    initAnalyticsEvents();

    // Forms
    $('form#comment-form input[type=submit]')
    .after('<div class="submit-progress"><img src="/sites/all/themes/tesla/images/ajax-loader-bar.gif" alt="Loading, please wait" /></div>')
    .click(function() {
            $(this).hide()
            .next('.submit-progress').show();
    });

    // Country Selector
    $('#tesla-country-selector .form-submit').hide();
    $('#tesla-country-selector #edit-country').change(function() {
        if ($(this).val() != '') {
            $('#tesla-country-selector').submit();            
        }
    });

    // Shop subnav link -- open in new window
    $('.menu-16276 a').attr('target','_new')

    // Locale specific
    attachLocaleHandlers();
    
    // Homepage
    initHome();

    // Fade alerts
    messagesBye = setTimeout(fadeAlerts, 4000);

    // Press page styling
    $('#page-about-press #left-col .pane-title').addClass('style-header');

    $('.typekit-badge').hide();

});

/*
 * Do this stuff when the page is loaded -- any visible transistions
 */
$(window).load(function() {

    // fade in any tooltips
    $('.hover_tooltip').fadeIn(1500);

    repositionFooter();

});

// HOME PAGE
//if ($.fn.cycle) {
//	var heroLeft = 0;
//	$.fn.cycle.transitions.fade2 = function($cont, $slides, opts) {
//		$slides.not(':eq('+opts.currSlide+')').css('opacity',0);
//		opts.before.push(function(curr,next,opts) {
//			$.fn.cycle.commonReset(curr,next,opts);
//			opts.cssBefore.opacity = 0;
//		});
//		opts.animIn    = { opacity: 1 };
//		opts.animOut   = { opacity: 0 };
//		opts.cssBefore = { top: 0, left: heroLeft, width: 1270 };
//	}
//        //jQ does not distinguish chrome from safari
//        $.browser.chrome = /chrome/.test(navigator.userAgent.toLowerCase());
//
//	function reposHero () {
//		var element =  $('#views_slideshow_singleframe_teaser_section_homepage_slideshow-default > div:not(.views_slideshow_singleframe_hidden)');
//		var wClient = $(window).width();
//		//var wElement = element.width();
//		var adjust = (wClient - 1270) / 2;
//
//		if ($.browser.safari) {
//			heroLeft = adjust;
//		} else {
//			heroLeft = (adjust < 0) ? adjust : 0;
//		}
//		element.css('left', heroLeft+"px");
//	}
//}

